package com.lanswon.qzsmk.service.systemManageService.impl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.HttpResponseException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.lanswon.qzsmk.exception.ApplicationException;
import com.lanswon.qzsmk.exception.ErrorCode;
import com.lanswon.qzsmk.exception.InventoryException;
import com.lanswon.qzsmk.annotation.SystemServiceLog;
import com.lanswon.qzsmk.base.CardContants;
import com.lanswon.qzsmk.base.DwzPage;
import com.lanswon.qzsmk.base.ListPageUtil;
import com.lanswon.qzsmk.base.PathContants;
import com.lanswon.qzsmk.dao.AppOpenRegMapper;
import com.lanswon.qzsmk.dao.ApplyBatchInfoMapper;
import com.lanswon.qzsmk.dao.CardBatchMapper;
import com.lanswon.qzsmk.dao.CardControlMapper;
import com.lanswon.qzsmk.dao.CardDataMapper;
import com.lanswon.qzsmk.dao.CardManageMapper;
import com.lanswon.qzsmk.dao.CardNoGeneratedMapper;
import com.lanswon.qzsmk.dao.CardPhysicsTypeMapper;
import com.lanswon.qzsmk.dao.CardProdunctDefinitionMapper;
import com.lanswon.qzsmk.dao.CardStockQuantityMapper;
import com.lanswon.qzsmk.dao.CardTaskMapper;
import com.lanswon.qzsmk.model.ActiveUser;
import com.lanswon.qzsmk.model.CardBatch;
import com.lanswon.qzsmk.model.CardControl;
import com.lanswon.qzsmk.model.CardData;
import com.lanswon.qzsmk.model.CardManage;
import com.lanswon.qzsmk.model.CardNoGenerated;
import com.lanswon.qzsmk.model.CardPhysicsType;
import com.lanswon.qzsmk.model.CardProdunctDefinition;
import com.lanswon.qzsmk.model.CardTask;
import com.lanswon.qzsmk.model.CooperationCompany;
import com.lanswon.qzsmk.model.PrimaryCardInfo;
import com.lanswon.qzsmk.model.StockDetail;
import com.lanswon.qzsmk.model.StockSum;
import com.lanswon.qzsmk.model.StorageDetail;
import com.lanswon.qzsmk.model.StorageModeDefinition;
import com.lanswon.qzsmk.model.StorageReg;
import com.lanswon.qzsmk.service.systemManageService.InventoryManagementService;
import com.lanswon.qzsmk.util.CommonUtil;
import com.lanswon.qzsmk.util.FileUtil;
import com.lanswon.qzsmk.util.ReadproUtil;
import com.lanswon.qzsmk.util.inventoryUtil.CheckFileUtil;
import com.lanswon.qzsmk.util.inventoryUtil.CreatePDFUtil;
import com.lanswon.qzsmk.util.inventoryUtil.DateAndStampUtil;
import com.lanswon.qzsmk.util.inventoryUtil.GetInventoryRecordNoUtil;
import com.lanswon.qzsmk.util.inventoryUtil.ListTurnToSet;
import com.lanswon.qzsmk.util.inventoryUtil.ParseFilePath;
import com.lanswon.qzsmk.util.pdfutil.TempletTicket;
import com.lanswon.qzsmk.vo.ApplyBatchInfo;
import com.lanswon.qzsmk.vo.CardInfoAndCustomerInfo;
import com.lanswon.qzsmk.vo.CardStockQuantityVo;
import com.lanswon.qzsmk.vo.DistributeDetailInfo;
import com.lanswon.qzsmk.vo.DistributeInfo;
import com.lanswon.qzsmk.vo.QueryIncomingAndOutGoing;
import com.lanswon.qzsmk.vo.RequestAndReturnRegInfoByEmpVo;
import com.lanswon.qzsmk.vo.ResponseCardFileVo;
import com.lanswon.qzsmk.vo.ResponseCardInfo;
import com.lanswon.qzsmk.vo.ResponseCardInfoForRBJM;
import com.lanswon.qzsmk.vo.StorageRegRecVo;
import com.lanswon.qzsmk.vo.StorageRegVo;
import com.lanswon.qzsmk.vo.TableVo;
import com.lowagie.text.pdf.PdfPTable;
import com.lanswon.qzsmk.dao.CooperationCompanyMapper;
import com.lanswon.qzsmk.dao.OrgMapper;
import com.lanswon.qzsmk.dao.PrimaryCardInfoMapper;
import com.lanswon.qzsmk.dao.StockDetailMapper;
import com.lanswon.qzsmk.dao.StockSumMapper;
import com.lanswon.qzsmk.dao.StorageDetailMapper;
import com.lanswon.qzsmk.dao.StorageModeDefinitionMapper;
import com.lanswon.qzsmk.dao.StorageRegMapper;
import com.lanswon.qzsmk.dao.UserMapper;

import ch.qos.logback.classic.Logger;

@Service
@Transactional
public class InventoryManagementServiceImpl implements InventoryManagementService{
	
	@Autowired
	CardTaskMapper ctm;
	
	@Autowired
	ApplyBatchInfoMapper abim;
	
	@Autowired
	CardProdunctDefinitionMapper cpdm;
	
	@Autowired
	CooperationCompanyMapper coopcm;
	
	@Autowired
	CardControlMapper cardControlMap;
	
	@Autowired
	CardBatchMapper cbm;
	
	@Autowired
	PrimaryCardInfoMapper pcim;
	
	@Autowired
	StockDetailMapper stockdm;
	
	@Autowired
	StockSumMapper ssm;
	
	@Autowired
	StorageRegMapper srm;
	
	@Autowired
	StorageDetailMapper sdm;
	
	@Autowired
	CooperationCompanyMapper ccm;
	
	@Autowired
	CardDataMapper cdm;
	
	@Autowired
	CardPhysicsTypeMapper cptm;
	
	@Autowired
	AppOpenRegMapper aorm;
	
	@Autowired
	GetInventoryRecordNoUtil inventoryRecordNoUtil;

	@Autowired
	CheckFileUtil checkFileUtil;
	
	@Autowired
	ListTurnToSet listUtil; 
	
	@Autowired
	ParseFilePath parseFile;
	
	@Autowired
	StorageModeDefinitionMapper smdm;
	
	@Autowired
	CardStockQuantityMapper csqm;
	
	@Autowired
	OrgMapper orgm;
	
	@Autowired
	CardManageMapper cmm;
	
	@Autowired
	CardNoGeneratedMapper cardNoGerateMapper;
	
	@Autowired
	UserMapper userMapper;
	
	//20180814鱼洲杰修改
	//private final static Map<String, Object> map=ReadproUtil.readPro();
	private final static Logger logger = (Logger) LoggerFactory.getLogger(InventoryManagementServiceImpl.class);
	
	  String INCOMING_PATH = ReadproUtil.INCOMING_PATH;

	  String INCOMING_FILE_SUFFIX = ReadproUtil.INCOMING_FILE_SUFFIX;

	  String RESPONSESUCCESS_PATH = ReadproUtil.RESPONSESUCCESS_PATH;

	  String BLANK_REJECT_TASK_PATH = ReadproUtil.BLANK_REJECT_TASK_PATH;
	
	  String BLANK_REJECT_TASK_RECEIVED_PATH = ReadproUtil.BLANK_REJECT_TASK_RECEIVED_PATH;
	
	  String REJECT_DISTRIBUTETASK_PATH = ReadproUtil.REJECT_DISTRIBUTETASK_PATH;
	
	  String REJECT_DISTRIBUTSUCCESS_PATH = ReadproUtil.REJECT_DISTRIBUTSUCCESS_PATH;
	
	  String CREDENCIAL_PATH = ReadproUtil.CREDENCIAL_PATH;
	
	  String IP_ADDRESS = ReadproUtil.IP_ADDRESS;
	/**
	 * 编号1-1-1 
	 * 功能：初始化或者按条件查询制卡文件夹下的所有信息，包括制卡批号，供应商等信息
	 * @throws IOException 
	 */
	@SystemServiceLog(description = "查询返回的制卡文件信息")
	public DwzPage<ResponseCardFileVo> queryPurchaseCardFiles(Map<String, String> tMap,int currentPage,int pageSize) throws IOException {
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		/*5.map,一个供应商，对应一个文件列表，每个文件对应一个卡产品*/
		Map<String,List<String>> fileMap = new HashMap<String,List<String>>();
		/*6.List,存放返回页面信息的列表*/
		List<ResponseCardFileVo> pageInfoList = new ArrayList<>();
		/*7.返回的制卡信息*/
		ResponseCardFileVo RCFV = null;
		//20180801  惠国磊  以下一行
		//获取键值对（制卡商，制卡文件列表）
		fileMap = parsePath(INCOMING_PATH,INCOMING_FILE_SUFFIX,tMap);
//		fileMap = parsePath(FileUtil.responseFile,FileUtil.responseFileSuffix,tMap);
		logger.debug("文件列表==>"+fileMap);
		
		Set<Map.Entry<String,List<String>>> entrySet = fileMap.entrySet();
		for(Map.Entry<String,List<String>> entry:entrySet){
			//制卡商列表
			String responseCompanyNo = entry.getKey();
			logger.debug("文件夹中的信息==>"+entry.getKey()+">>"+entry.getValue().toString());
			for(int i=0;i<entry.getValue().size();i++){
				RCFV = new ResponseCardFileVo();
				RCFV.setResponseCompanyNo(responseCompanyNo);
				RCFV.setResponseFileNo(entry.getValue().get(i));
				pageInfoList.add(RCFV);
			}	
		}
		
		//根据分页情况，获取list
		
		List<ResponseCardFileVo> pageInfoReturnList = new ArrayList<ResponseCardFileVo>();
		Integer startLine = (currentPage-1)*pageSize;
		logger.debug("startLine==>"+startLine);
		//鱼洲杰修改
		int totalCount=0;
		if(activeUser.getBranchNo().equals("10000000")){
		if(pageInfoList.size()<=pageSize){
			pageInfoReturnList = pageInfoList;
		}else{
			if((pageInfoList.size()-startLine)>pageSize){
				pageInfoReturnList = pageInfoList.subList(startLine, startLine+pageSize);
			}else{
				pageInfoReturnList = pageInfoList.subList(startLine, pageInfoList.size());
			}	
		}
		logger.debug("pageInfoReturnList.size()==>"+pageInfoReturnList.size());
		totalCount=pageInfoList.size();
		}
		//页面列表信息
		
		DwzPage<ResponseCardFileVo> dp = new DwzPage<ResponseCardFileVo>(currentPage, pageSize ,totalCount);
		dp.setList(pageInfoReturnList);
		return dp;
	}
	
	/**
	 * 编号1-1-2
	 * 功能：读取指定路径下，所有的文件,及信息
	 * @param filePath  文件路径
	 * @param suffix  文件后缀名
	 * @return
	 * @throws IOException 
	 */
	@SystemServiceLog(description = "获取文件信息")
	private Map<String,List<String>> parsePath(String filePath,String suffix,Map<String, String> tMap) throws IOException{
			//制卡文件列表
			List<String> fileList = new ArrayList<String>();
			//key是供应商，value是对应的文件列表
			Map<String,List<String>> fileMap = new HashMap<String,List<String>>();
			String makeCardNo = tMap.get("makeCardNo");
			//如果指定供应商，返回指定供应商路径下的文件
			String companies = tMap.get("companies");
			//这里需要通过供应商代码查供应商名字
			if("".equals(makeCardNo)||null==makeCardNo){
				makeCardNo="";	
			}
			logger.debug("makeCardNo===>"+makeCardNo);
			logger.debug("companies===>"+companies);
			//如果查询条件，给定供应商代码,解析指定供应商的文件夹
			if(!"".equals(companies)&& null!=companies){
				String companyName = coopcm.queryCooperationCompanyByCompanyNo(companies).getCompanyName();
				filePath = filePath +File.separator+companyName;
				logger.debug("filePath1==>"+filePath);
				fileMap = getFileMap(filePath,suffix,makeCardNo,companyName,fileMap);
			//如果供应商查询值为空，遍历所有文件夹
			}else{
				File targetFile = new File(filePath);
				logger.debug("filePath==>"+filePath);
				logger.debug("targetFile==>"+targetFile);
				if(targetFile.exists()){
					//找到路径下所有文件及文件夹
					File[] files = targetFile.listFiles();
					for(File file:files){
						//是文件夹则继续解析文件夹下内容
						if(file.isDirectory()){
							//制卡商名称
							String subFileNameAsCompany  = file.getName();
							logger.debug("subFileName==>"+subFileNameAsCompany);
							String subFilePath = filePath+File.separator+subFileNameAsCompany;
							logger.debug("subFilePath==>"+subFilePath);
							//如果文件名和查询的制卡文件号相同，那么清空map，再进行操作，并且，跳出循环
							fileMap = getFileMap(subFilePath,suffix,makeCardNo,subFileNameAsCompany,fileMap);
							logger.debug("fileMap==>"+fileMap);
							//如果查询的制卡文件号已经找到，跳出循环，立即返回
							if(fileMap.get(subFileNameAsCompany)!=null && fileMap.get(subFileNameAsCompany).contains(makeCardNo)){
								fileMap.clear();
								fileList.clear();
								fileList.add(makeCardNo);
								fileMap.put(subFileNameAsCompany,fileList);
								break;
							}
						}
					}
				}	
			}
			return fileMap;
		}
	
	/**
	 * 编号1-1-3
	 * 功能：获取（供应商，制卡文件列表）信息
	 * @param filePath 文件夹路径
	 * @param suffix 文件后缀名
	 * @param makeCardNo 制卡任务号
	 * @param companies 制卡商
	 * @return
	 * @throws IOException 
	 */
	@SystemServiceLog(description = "获取信息")
	 private Map<String, List<String>> getFileMap(String filePath, String suffix, String makeCardNo,String companies,Map<String, List<String>> fileMap) throws IOException {
			//制卡文件列表
			List<String> fileList = new ArrayList<String>();
			logger.debug("文件路径是==>"+filePath);
			File targetFile = new File(filePath);
			if(targetFile.exists()){
				File[] files = targetFile.listFiles();
				//如果文件路径下存在文件，读出所有文本文件信息
				if(files.length>0){
					fileList = getFileList(files,makeCardNo,suffix);
				}
				
				if(fileList.size()>0){
					fileMap.put(companies,fileList);
				}
			}
			return fileMap;
		}
	
   /**
	 * 编号1-1-4
	 * 功能：获取对应文件夹下的文本文件名称列表
	 * @param files 文件夹下所有文件
	 * @param makeCardNo 制卡任务号，对应画面的查询值，画面没有输入时为""
	 * @return
 * @throws IOException 
	 */
	@SystemServiceLog(description = "获取对应文件下名称")
	private List<String> getFileList(File[] files, String makeCardNo,String suffix) throws IOException {
		logger.debug("makecardNo===>"+makeCardNo);
		//制卡文件列表
		List<String> fileList = new ArrayList<String>();
		for(File file:files){
			//如果文件不是文件夹
			if(!file.isDirectory()){
				String fileName = file.getName();
				logger.debug("fileName==>"+fileName);
				//如果文件是txt后缀,则进行操作
				if(fileName.endsWith(suffix)){
					fileName = fileName.substring(0, fileName.length()-4);
					//将文件名第一个字符替换成R
					String branchNo = fileName.substring(8);
					logger.debug("branchNo==>"+branchNo);
					//判断该文件是否被导入过了，状态是否是已制卡结束 5
					if(checkFileUtil.checkFileName(fileName) && checkFileUtil.checkFileFormat(file) 
							&& checkFileUtil.checkFileStatus(fileName)){
						//如果是查询的制卡文件名匹配,先清空文件列表，再返回
						//这里的makeCardNo是画面的查询值
						logger.debug("进入文件列表方法");
						if(makeCardNo!=null&&!"".equals(makeCardNo)){
							if(makeCardNo.equals(fileName)){
								fileList.clear();
								fileList.add(fileName);
								return fileList;
							}else{
								fileList.clear();
								continue;
								//return fileList;
							}
						}else{
							fileList.add(fileName);
						}
						logger.debug("fileList===>"+fileList.toString());
					}
				}
			}
		}
		return fileList;
	}
	 
	/**
	 * 编号：1-4-1
	 * 功能：编辑文件列表，传递到下个画面，列表元素包含（供应商，制卡批号）
	 * @param responseFiletasked
	 * @return
	 */
	@SystemServiceLog(description = "编辑文件列表")
	public List<Map<String, String>> getMakeCardFileNoList(String[] responseFiletasked) {
		List<Map<String, String>> makeCardFileNoList = new ArrayList<Map<String, String>>();
		for (int j = 0; j < responseFiletasked.length; j++) {
			logger.debug("传入的选中信息是==>" + responseFiletasked[j]);
		}
		for (int i = 0; i < responseFiletasked.length; i++) {
			logger.debug("param==>" + responseFiletasked[i]);
			int index = responseFiletasked[i].indexOf("\\");
			String responseCompanyNo = responseFiletasked[i].substring(0, index);
			String responseFileNo = responseFiletasked[i].substring(index + 1);
			logger.debug("responseCompanyNo==>" + responseCompanyNo);
			logger.debug("responseFileNo==>" + responseFileNo);
			Map<String, String> map = new HashMap<String, String>();
			map.put("responseCompanyNo", responseCompanyNo);
			map.put("responseFileNo", responseFileNo);
			makeCardFileNoList.add(map);
		}
		return makeCardFileNoList;
	}	
	
	/**
	 * 编号：1-6-1
	 * 功能：解析出（入库总数量，（卡产品，卡数量，制卡批号）列表）信息
	 * @param map 选中的文件信息
	 * @return
	 */
	@SystemServiceLog(description = "解析出信息")
	public List<Map<String, Object>> getIncomingDetail(Map<String, Object> map) {
		//获取前画面传过来的供应商+制卡文件号
		List<Map<String,String>> fileList = new ArrayList<Map<String,String>>();
		fileList = (List<Map<String, String>>) map.get("fileInfoList");
		List<String> pathList = new ArrayList<String>();
		//存放库存单号的map
		Map<String,Object> storageNoMap= new HashMap<String,Object>();
		//返回的list对象
		List<Map<String,Object>> retrunList = new ArrayList<Map<String,Object>>();
		for(int i=0;i<fileList.size();i++){
			String filePath = null;
			String responseCompanyNo = fileList.get(i).get("responseCompanyNo");
			String responseFileNo = fileList.get(i).get("responseFileNo");
			logger.debug("获取前画面传过来的供应商==>"+responseCompanyNo);
			logger.debug("获取前画面传过来的文件号==>"+responseFileNo);
			filePath = responseCompanyNo+"\\"+responseFileNo;
			pathList.add(filePath);
		}
		//2.获取每个文件的详细信息：卡产品名称，卡数量，供应商，卡类型，返回文件信息？？
		for(int i=0;i<pathList.size();i++){
			Map<String,Object> detailMap = null;
			
			String param = pathList.get(i);
			//map中的信息：rci对象，company，requireAmount，successAmount
			detailMap = queryResponseFileDetail(param);
			logger.debug("detailMap==>"+detailMap);
			retrunList.add(detailMap);
		}
		
		
		//1.获取入库单号,将入库单号显示到画面上
		/*String storageNo = inventoryRecordNoUtil.getStorageNo();
		logger.debug("storageNo===>"+storageNo);
		storageNoMap.put("storageNo", storageNo);
		retrunList.add(storageNoMap);*/
		return retrunList;
	}
	
	/**
	 * 编号：1-6-2
	 * 功能：通过路径，解析出（入库总数量，（卡产品，卡数量，制卡批号）列表）信息
	 * @param param 文件名和路径
	 * @return
	 */
	@SystemServiceLog(description = "通过路径解析信息")
	public Map<String,Object> queryResponseFileDetail(String param) {
		//读取文件每行，使用的列表变量
		List<String> list = new ArrayList<String>();
		//装入每个制卡文件详细信息的对象列表
		List<ResponseCardInfo> objectList = new ArrayList<ResponseCardInfo>();
		//装入每个制卡文件详细信息的对象列表
		List<ResponseCardInfoForRBJM> objectBJMList = new ArrayList<ResponseCardInfoForRBJM>();
		//返回的map
		Map<String,Object> map = new HashMap<String,Object>();
		//卡主类型代码
		String cardPrimaryCode = null;
		//所有的卡号和制卡结果组成的key,value值
		Map<String,String> cardResultMap = new HashMap<String,String>();
		
		logger.debug("前画面传过来的路径==>"+param);
		int index = param.indexOf("\\");
		logger.debug("index==>"+index);
		String company = param.substring(0, index);
		//制卡返回文件号
		String makeCardNo = param.substring(index+1);
		//20180529 惠国磊  以下行
		String batchMakeNo = makeCardNo.substring(8);
		
		logger.debug("制卡批号是==>"+batchMakeNo);
		logger.debug("制卡文件号是==>"+makeCardNo);
	//	String filePath = FileUtil.responseFile + "\\"+param+".txt";
		String filePath = INCOMING_PATH + File.separator+company+File.separator+makeCardNo+".txt";
		logger.debug("拼接成的返回文件的路径==>"+filePath);
		File targetFile = new File(filePath);
		
		if(targetFile.exists()){		
			FileInputStream fis = null;
			InputStreamReader isr = null;
			BufferedReader br = null;
			try {
				fis = new FileInputStream(targetFile);
				isr = new InputStreamReader(fis, "GBK");
				br = new BufferedReader(isr);
				String line = "";
				while ((line = br.readLine()) != null) {
		               list.add(line);
		        }  
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				if(br!=null){
					try {
						br.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(isr!=null){
					try {
						isr.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(fis!=null){
					 try {
						fis.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		//制卡文件要求的总数量；
		int cardAmount = list.size()-1;
		//初始化 制卡成功的数量   ；=制卡结果为0的总和
		int successAmount = 0;
		//3:Q.市民卡卡面号 , 8:Q.制卡结果  9:Q.制卡失败原因   26:3F00.0005.卡主类型	
		logger.debug("文件行数==>"+list.size());
		
		
		//需要判断是不记名的文件还是记名文件
		
		String cardType = makeCardNo.substring(0,4);
		logger.debug("cardType==>"+cardType);
		
		if("QJMK".equals(cardType)){
			for(int i=1;i<list.size();i++){
				ResponseCardInfo rci = new ResponseCardInfo();
				String[] subColumn = list.get(i).split("\\|");
				//20190108 hgl 
				//获取非接触芯片号
				rci.setUntouchChipNo(subColumn[1]);
				//获取非接触pin码
				rci.setUntouchPin(subColumn[2]);
				//获取卡片序列号
				rci.setCardSerialNo(CommonUtil.AsciiStringToString(subColumn[5]));
				//获取城市代码
				rci.setCityCode(subColumn[24]);
				
				//设置制卡文件名称
				rci.setMakeCardFileName(makeCardNo);
				//设置制卡批号
				rci.setBatchMakeNo(batchMakeNo);
				//获取市民卡号
				rci.setCitizenCardNo(CommonUtil.AsciiStringToString(subColumn[3]));
				//获取卡主类型代码
				if(cardPrimaryCode==null || "".equals(cardPrimaryCode)){
					cardPrimaryCode = subColumn[26];
				}
				//获取卡主类型
				rci.setCardPrimaryCode(subColumn[26]);
				//获取制卡结果
				rci.setResultOfMakeCd(subColumn[8]);
				if("0".equals(rci.getResultOfMakeCd())){
					successAmount = successAmount+1;
				}
				cardResultMap.put(subColumn[3], subColumn[8]);
				//获取制卡失败原因
				rci.setCauseOfFailure(subColumn[9]);
				objectList.add(rci);
			}
			map.put("fileDetail", objectList);
			map.put("company", company);
			//制卡要求总数量
			map.put("requireAmount", cardAmount);
			//制卡返回成功数量
			map.put("successAmount", successAmount);
			//卡产品名称（同一个文件，卡产品名称一样）
	//		String cardPName = queryPrimaryCode(cardPrimaryCode).getCardPName();
	//		map.put("cardPName", cardPName);
			//卡产品代码（同一个文件，卡产品代码一致）
	//		String cardPCode = queryPrimaryCode(cardPrimaryCode).getCardPCode();
	//		map.put("cardPCode", cardPCode);
			
			//通过文件号码，查询所申请的卡产品的名称和代码
			List<String> batchMakerNoList = new ArrayList<String>();
			batchMakerNoList.add(batchMakeNo);
			CardTask cardTaskObj = ctm.queryTaskInfo(batchMakerNoList).get(0);
			CardData cardDataObj = cdm.queryCardDataByCardTaskNo(cardTaskObj.getCardTaskNo());
			String cardPCode = (String)cardDataObj.getCardpCode();
			String cardPhysicType = (String)cardTaskObj.getTaskName().substring(3,4);
			map.put("cardPhysicType", cardPhysicType);
			map.put("cardPCode", cardPCode);
			String cardPName = cpdm.queryCardPCode(cardDataObj.getCardpCode()).getCardpName();
			map.put("cardPName", cardPName);
			//卡产品主类型代码（同一个文件，卡主类型代码一致）
	//		map.put("primaryCode", cardPrimaryCode);
			//将卡号和对应的制卡结果，装入map
			map.put("cardResult", cardResultMap);
			map.put("cardTypeFlag", "QJMK");
			
		//不记名文件是一个任务一个制卡批次
		}else if("QBJM".equals(cardType)){
				ResponseCardInfoForRBJM rciBJM = new ResponseCardInfoForRBJM();
				String[] subColumn = list.get(1).split("\\|",-1);
				//设置制卡文件名称
				rciBJM.setMakeCardFileName(makeCardNo);
				//设置制卡批号
				rciBJM.setBatchMakeNo(batchMakeNo);
				//设置制卡任务号
				rciBJM.setCardTaskNo(subColumn[1]);
				//设置制卡总数量
				rciBJM.setTotalAmount(subColumn[2]);
				//设置制卡成功数量
				rciBJM.setSuccessAmount(subColumn[3]);
				//设置制卡失败数量
				rciBJM.setFailAmount(subColumn[4]);
				//设置失败卡号
				String faliCards = subColumn[5];
				rciBJM.setFailCards(faliCards);
			//查询出该批次的卡号起始段
			List<CardData> cardDataLists = cdm.queryCardDataByCardTaskNo_list(subColumn[1].trim());
			logger.debug("cardDataLists==>"+cardDataLists.size());
			CardTask cardTaskObj = ctm.queryCardTaskByCardTaskNo(subColumn[1].trim());
			String cardPhysicType = cardTaskObj.getTaskName().substring(3,4);
			//如果存在卡号段
			if(cardDataLists.size()>0){
				map.put("startNo", cardDataLists.get(0).getCitizenCardNo());
				map.put("endNo", cardDataLists.get(cardDataLists.size()-1).getCitizenCardNo());	
			}else{
				map.put("startNo", "");
				map.put("endNo", "");
			}
			map.put("cardPhysicType", cardPhysicType);
			map.put("fileDetail", rciBJM);
			map.put("cardTypeFlag", "QBJM");
			map.put("company", company);
			//通过任务号，查询卡产品的名称和代码
			CardData cardDataObj = cdm.queryCardDataByCardTaskNo(subColumn[1]);
			map.put("cardPCode", cardDataObj.getCardpCode());
			CardProdunctDefinition cardDefObj  = cpdm.queryCardPCode(cardDataObj.getCardpCode());
			map.put("cardPName", cardDefObj.getCardpName());
			map.put("successAmount", rciBJM.getSuccessAmount());
			map.put("requireAmount", rciBJM.getTotalAmount());
		}
		return map;
	}
	
	/**
	 * 编号：1-9-1
	 * 功能：入库，数据库操作
	 * @param serializeForm 表单内容
	 * @return resultMap 入库单打印需要的参数
	 * @throws InventoryException 
	 * @throws ApplicationException 
	 * @throws HttpResponseException 
	 * @throws Exception 
	 */
	@SystemServiceLog(description = "入库操作")
	@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
	public Map<String,Object> updateInfo(String serializeForm) throws InventoryException  {
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		//每个批次号对应的供应商列表
		List<String> companyList = new ArrayList<String>();
		//制卡批次号
		List<String> makeCardNoList = new ArrayList<String>();
		//每个批次的数量列表
		List<Integer> amountListByBtach = new ArrayList<Integer>();
		//制卡任务数量
		List<Integer> amountListByTask = new ArrayList<Integer>();
		//每个产品的数量列表
		List<String> cardPCodeList = new ArrayList<String>();	
		//卡产品名称的列表
		List<String> cardPNameList = new ArrayList<String>();
		//返回批次文件中，卡号对应的制卡结果
		Map<String,String> cardResultMap = new HashMap<String,String>();
		//返回打印pdf所需要的Map
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		//记录库存的卡产品是成品卡还是空白卡
		List<String> cardStockTypeList = new ArrayList<String>();
		Map<String,Integer> taskAndAmount = new HashMap<String,Integer>();
		
		Map<String,String> map = getKeyValueMap(serializeForm);
		
		//20190104 hgl
		List<String> totalRBJMCitizenCardNoList = new ArrayList<String>();
		List<String> totalRJMKCitizenCardNoList = new ArrayList<String>();
		Map<String,List<String>> batchNoAndCardNoMap = new HashMap<String,List<String>>();
		
		
		logger.debug("map==>"+map);
		//取出文件中的卡号组，取出制卡结果，重新装入map,key=市民卡号，value=制卡结果
		String citizenCardN = map.get("citizenCardNo");
		String cardResult = map.get("cardResult");
		String cardPCode = map.get("cardPCodeByIncomingReg");
		String cardTaskNos = map.get("cardTaskNoByIncomingReg");
		String makeCardFileNames = map.get("makeCardFileName");
		String cardPhysicTypes = map.get("cardPhysicTypeByIncomingReg");
		String cardSerialNos = map.get("cardSerialNoByIncomingReg");
		String untouchChipNos = map.get("untouchChipNoByIncomingReg");
		String untouchPins = map.get("untouchPinByIncomingReg");
		String cityCodes = map.get("cityCodeByIncomingReg");
		//20190104 hgl
		String batchMakeNos = map.get("batchMakeNo");
		String[] batchMakeNoArray = batchMakeNos.split("\\$");
		String[] citizenCardNArrays = citizenCardN.split("\\$");
		String[] cardResultArrays = cardResult.split("\\$");
		String[] cardPCodeArrays = cardPCode.split("\\$");
		String[] cardTaskNoArrays = cardTaskNos.split("\\$");
		String[] makeCardFileNameArray = makeCardFileNames.split("\\$");
		String[] cardPhysicTypeArray = cardPhysicTypes.split("\\$");
		String[] cardSerialNosArray = cardSerialNos.split("\\$");
		String[] untouchChipNosArray = untouchChipNos.split("\\$");
		String[] untouchPinsArray = untouchPins.split("\\$");
		String[] cityCodesArray = cityCodes.split("\\$");
		
		for(int n=0;n<citizenCardNArrays.length;n++){
			String[] citizenCardNArry;
			String[] cardResultArry;
			String[] cardSerialNoArray;
			String[] untouchChipNoArray;
			String[] untouchPinArray;
			String[] cityCodeArray;
			String batchMakeNo = batchMakeNoArray[n];
			logger.debug("batchMakeNo==>"+batchMakeNo);
			if(makeCardFileNameArray[n]!=null && makeCardFileNameArray[n].startsWith("QBJM")){
				citizenCardNArry = citizenCardNArrays[n].split("~");
				List<String> successCitizenCardNoList = new ArrayList<String>();
				//增加每个卡号对应的结果
				String startNo = citizenCardNArry[0].substring(5);
				String endNo = citizenCardNArry[1].substring(5);
				//查找出对应的卡号list,再赋值0
				List<String> citizenNolist = cdm.queryCitizenCardNoByStartEnd(startNo,endNo,cardTaskNoArrays[n]);
				for(int j=0;j<citizenNolist.size();j++){
					cardResultMap.put(citizenNolist.get(j),"0");
					totalRBJMCitizenCardNoList.add(citizenNolist.get(j));
					successCitizenCardNoList.add(citizenNolist.get(j));
				}
				if(!"".equals(cardResultArrays[n])&& cardResultArrays[n]!=null&&!"no".equals(cardResultArrays[n])){
					//判断是否有制卡失败的卡号，如果有，按逗号分割。
					if(cardResultArrays[n].indexOf("#")>0){
						cardResultArry = cardResultArrays[n].split("#");
					}else{
						cardResultArry = new String[]{cardResultArrays[n]};
					}
					
					for(int m=0;m<cardResultArry.length;m++){
						cardResultMap.put(cardResultArry[m],"1");
						successCitizenCardNoList.remove(cardResultArry[m]);
					}
				}
				logger.debug("cardResultMap==>"+cardResultMap);
				Collections.sort(successCitizenCardNoList,new Comparator<String>()
				{	
					@Override
					public int compare(String o1, String o2) {
						int compare1 = Integer.parseInt(o1.substring(5,12));
				        int compare2 = Integer.parseInt(o2.substring(5,12));
				        return compare1 - compare2;
					}

				});
				batchNoAndCardNoMap.put(batchMakeNo,successCitizenCardNoList);
				
			}
			if(makeCardFileNameArray[n]!=null && makeCardFileNameArray[n].startsWith("QJMK")){
				citizenCardNArry = citizenCardNArrays[n].split("#");
				cardResultArry = cardResultArrays[n].split("#");
				cardSerialNoArray = cardSerialNosArray[n].split("#");
				untouchChipNoArray = untouchChipNosArray[n].split("#");
				untouchPinArray = untouchPinsArray[n].split("#");
				cityCodeArray = cityCodesArray[n].split("#");
				List<String> successCitizenCardNoList = new ArrayList<String>();
				for(int k = 0;k<citizenCardNArry.length;k++){
					String citizenCardNo = citizenCardNArry[k];
					String cardSerialNo = cardSerialNoArray[k];
					String untouchChipNo = untouchChipNoArray[k];
					String untouchPin = untouchPinArray[k];
					String cityCode = cityCodeArray[k];
					String cardResultOfMakeing = cardResultArry[k];
					cardResultMap.put(citizenCardNo, cardResultOfMakeing);
					totalRJMKCitizenCardNoList.add(citizenCardNo);
					if("0".equals(cardResultOfMakeing)){
						String citizenCardNoCombination = citizenCardNo+"#"+cardSerialNo+"#"
														+untouchChipNo+"#"+untouchPin+"#"+cityCode;
						successCitizenCardNoList.add(citizenCardNoCombination);
					}
				}
				Collections.sort(successCitizenCardNoList,new Comparator<String>()
				{	
					@Override
					public int compare(String o1, String o2) {
						int compare1 = Integer.parseInt(o1.substring(5,12));
				        int compare2 = Integer.parseInt(o2.substring(5,12));
				        return compare1 - compare2;
					}

				});
				batchNoAndCardNoMap.put(batchMakeNo,successCitizenCardNoList);
			}	
		}
		
		
		logger.debug("制卡文件中的卡号对应结果键值对==>"+cardResultMap);
		
		
		//需要查询是否有已有重复的卡号，如果有，停止入库
		if(totalRJMKCitizenCardNoList.size()>0){
			List<CardData> existCitizenCardNo = cdm.queryCardDataByCitizenCardNoList(totalRJMKCitizenCardNoList);
			if(existCitizenCardNo.size()>0){
				throw new InventoryException("制卡文件卡数据和系统已有卡数据重复！");
			}
		}

		//1.更新制卡批次表信息
		//makeCardNoList：制作批次，empNo：操作柜员 ，myDate:接收日期
		//从解析的map中获取制卡文件号
		int fileLen = map.get("makeCardFileName").split("\\$").length;
		//当选中一个文件时
		if(fileLen==0){
			String makeCardNo = map.get("batchMakeNo");
			String amount = map.get("successAmount");
			String cardPName = map.get("cardPName");
			String company = map.get("company");
			String makeCardFileName = map.get("makeCardFileName");
			/*if(makeCardFileName.startsWith("QBJM")){
				cardStockTypeList.add("1");
			}else if(makeCardFileName.startsWith("QJMK")){
				cardStockTypeList.add("2");
			}*/
			makeCardNoList.add(makeCardNo);
			amountListByBtach.add(Integer.parseInt(amount));
			cardPCodeList.add(cardPCode);
			companyList.add(company);
			cardPNameList.add(cardPName);
		//选中多个文件时
		}else{
			String[] makeCardNos = map.get("batchMakeNo").split("\\$");
			String[] amountArray = map.get("successAmount").split("\\$");
			String[] cardCodeArray = map.get("cardPCodeByIncomingReg").split("\\$");
			String[] companyArray = map.get("company").split("\\$");
			String[] cardPNameArray = map.get("cardPName").split("\\$");
			String[] makeCardFileNameArrays = makeCardFileNames.split("\\$");
			for(int m=0;m<makeCardNos.length;m++){
				makeCardNoList.add(makeCardNos[m]);
				amountListByBtach.add(Integer.parseInt(amountArray[m]));
				cardPCodeList.add(cardCodeArray[m]);
				companyList.add(companyArray[m]);
				cardPNameList.add(cardPNameArray[m]);
				/*if(makeCardFileNameArrays[m].startsWith("QBJM")){
					cardStockTypeList.add("1");
				}else if(makeCardFileNameArrays[m].startsWith("QJMK")){
					cardStockTypeList.add("2");
				}*/
			}
		}
		//通过制卡批号，查询对应的制卡任务类型
		List<CardTask>  cardTaskList =  ctm.queryCardTaskTypeByBatchNoList(makeCardNoList);
		Map<String,String> taskTypeAndBatchNoMap = new HashMap<String,String>();
		for(int i =0;i<cardTaskList.size();i++){
			CardTask cardTaskObj = cardTaskList.get(i);
			String batchNo = cardTaskObj.getBatchMarkerNo();
			String taskType = cardTaskObj.getTaskType();
			taskTypeAndBatchNoMap.put(batchNo, taskType);
		}
		for(int j=0;j<makeCardNoList.size();j++){
			String taskType = taskTypeAndBatchNoMap.get(makeCardNoList.get(j));
			if("2".equals(taskType)){
				taskType = "1";
			}else if("1".equals(taskType)){
				taskType = "2";
			}
			cardStockTypeList.add(taskType);
		}
		String empNo = map.get("empNoByPCR");
		Date currentDate =  new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String dateStr = sdf.format(currentDate);
		Date myDate = null;
		try {
			myDate = sdf.parse(dateStr);
			logger.debug("myDate==>"+myDate.toString());
		} catch (ParseException e) {
			
			e.printStackTrace();
		}
		//更新制卡批次表信息
		//惠国磊 20180817 增加以下逻辑，判断将要入库的批次文件信息是否已经被接收，如果被接收了，那么给出提示
		//该批次已经被他人接收，不要重复提交，请返回首页
		List<String> receiveFlagList = cbm.queryCardBatchByBatchMarkerNoList(makeCardNoList);
		for(int i=0;i<receiveFlagList.size();i++){
			logger.debug("receiveFlagList==>"+receiveFlagList.get(i));
			if(!"".equals(receiveFlagList.get(i))&&receiveFlagList.get(i)!=null){
				
				throw new InventoryException("信息已入库，请返回首页刷新后继续操作！");
			}
		}
		int updateFlag = cbm.updateBatchByReturnInfo(makeCardNoList, empNo,myDate);		
		
		
		//2.更新制卡任务表的任务状态
		// 2.1查询出对应制卡批次号的所有任务编号
		List<CardTask> taskInfoList = new ArrayList<CardTask>();
		taskInfoList = ctm.queryTaskInfo(makeCardNoList);
		Map<String,String> taskABatch = new HashMap<String,String>();
		Map<String,String> taskAStatus = new HashMap<String,String>();
		List<String> taskList = new ArrayList<String>();
		if(taskInfoList.size()>0){
			String taskNos = "";
			for(int n=0;n<taskInfoList.size();n++){
				CardTask cardTaskObject = taskInfoList.get(n);
				String batchNo = cardTaskObject.getBatchMarkerNo();
				String taskStatus = cardTaskObject.getTaskStatus();
				String taskNo = cardTaskObject.getCardTaskNo();
				Integer amount = cardTaskObject.getRecordNum();
				if(taskABatch.containsKey(batchNo)){
					taskNos = taskNos + "#"+taskNo;
				}else{
					taskNos = taskNo;
				}
				//一个制卡批号所对应的任务号
				taskABatch.put(batchNo, taskNos);
				taskAStatus.put(taskNo, taskStatus);
				taskList.add(taskNo);
				taskAndAmount.put(taskNo, amount);
			}
		}
		logger.debug("制卡任务号==>"+taskList);
		logger.debug("(制卡批次，制卡任务编号列表)==>"+taskABatch);
		logger.debug("（制卡任务编号，制卡状态）==>"+taskAStatus);
		logger.debug("制卡任务数量==>"+taskAndAmount);
		
		// 更新任务表
		if(taskList.size()>0){
			int updateStatusFlag = ctm.updateSuccessTaskStatus(taskList);
		}
		
		//不记名卡不需要更新卡数据表，记名卡需要
		//更新卡数据表（插入卡号，卡片序列号等），更新卡控制表
		List<CardData> cardDataList = new ArrayList<CardData>();
		List<CardManage> cardMagList = new ArrayList<CardManage>();
		List<CardControl> cardControlObjList = new ArrayList<CardControl>();
		//通过制卡批号查询卡数据和卡控制对象
		List<ApplyBatchInfo> batchInfoList = abim.queryBatchInfoBymakeNoList(makeCardNoList);
		
		for(int i=0;i<batchInfoList.size();i++){
			ApplyBatchInfo applyBatchObj = batchInfoList.get(i);
			String batchMakeNo = applyBatchObj.getBatchMakeNo();
			String fileName = applyBatchObj.getBatchFileName();
			String rank = applyBatchObj.getRank();
			String citizenCardNoCombination = batchNoAndCardNoMap.get(batchMakeNo).get(Integer.parseInt(rank)-1);
			String citizenCardNo = null;
			if("RJMK".equals(fileName)){
				String[] citizenNoComArray = citizenCardNoCombination.split("#");
				CardData cardDataToUpdate = new CardData();
				cardDataToUpdate.setCardDataId(applyBatchObj.getCardDataId());
				cardDataToUpdate.setCitizenCardNo(citizenNoComArray[0]);
				cardDataToUpdate.setCardSeqNo(citizenNoComArray[1]);
				cardDataToUpdate.setChipsLessNo(citizenNoComArray[2]);
				cardDataToUpdate.setChipsLessPin(citizenNoComArray[3]);
				cardDataToUpdate.setCityCode(citizenNoComArray[4]);
				//后续增加插入信息……………………
				cardDataList.add(cardDataToUpdate);
				citizenCardNo = citizenNoComArray[0];
			}
			if("RBJM".equals(fileName)){
				citizenCardNo = citizenCardNoCombination;
			}
			
			CardManage cardMagToUpdate = new CardManage();
			String processId = UUID.randomUUID().toString().replace("-", "");
			cardMagToUpdate.setProcessId(processId);
			cardMagToUpdate.setApplyBranch(activeUser.getBranchName());
			cardMagToUpdate.setApplyBranchNo(activeUser.getBranchNo());
			cardMagToUpdate.setApplyDate(new Date());
			cardMagToUpdate.setApplyTellerNo(activeUser.getUserNo().toString());
			cardMagToUpdate.setBusinessNo("");
			cardMagToUpdate.setProcessCode(CardContants.CARD_PROC_INCOM);
			cardMagToUpdate.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_INCOM));
			cardMagToUpdate.setCitizenCardNo(citizenCardNo);
			cardMagToUpdate.setCardPosition(CardContants.CARD_POSITION_CENTRAL_STOREROOM);
			cardMagToUpdate.setCardStatus(CardContants.CARD_STATE_DISABLED);
		//	cme.setApplyWay("");// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
			cardMagList.add(cardMagToUpdate);
			
			CardControl cardControlObj = new CardControl();
			cardControlObj.setCardControlId(applyBatchObj.getCardControlId());
			cardControlObj.setCardPosition("1");
			cardControlObj.setClaimStatus("06");
			cardControlObj.setCurrProcId(processId);
			cardControlObj.setLastDate(currentDate);
			cardControlObj.setLastOperator(activeUser.getUserNo().toString());
			cardControlObjList.add(cardControlObj);
			
		}
		if(cardDataList.size()>0){
			cdm.batchUpdateByIncmoing(cardDataList);
		}
		
		cmm.batchInsert(cardMagList);
		cardControlMap.updateControlSuccess(cardControlObjList);		
		
		
		//更新卡号库
		//20190103 所有的卡号，排序，找出连续的卡号段
		if(totalRJMKCitizenCardNoList.size()>0){
			
			List<String[]> segmentUsedList = new ArrayList<String[]>();
			if(totalRJMKCitizenCardNoList.size()>1){
				segmentUsedList = listUtil.modifyCitizenNoList(totalRJMKCitizenCardNoList);
			}
			if(totalRJMKCitizenCardNoList.size()==1){
				String citizenCardNo = totalRJMKCitizenCardNoList.get(0);
				String startSegmentString = citizenCardNo.substring(5);
				segmentUsedList.add(new String[]{startSegmentString,startSegmentString});
			}		
			List<CardNoGenerated> CardNoGeneratedToUpdate = new ArrayList<CardNoGenerated>();
			for(int j=0;j<segmentUsedList.size();j++){
				String startNo = segmentUsedList.get(j)[0];
				String endNo = segmentUsedList.get(j)[1];
				//通过起始号和结束号查询卡号库
				List<CardNoGenerated>  cardNoGeneratedList = cardNoGerateMapper.querySegementByStartAndEnd(startNo,endNo);
				if(cardNoGeneratedList.size()==1){
					CardNoGenerated cngObj = cardNoGeneratedList.get(0);
					
					Integer usedAmount = cngObj.getUsedSegmentNo();
					Integer segAmount = cngObj.getNum();
					Integer toUpdateAmount = Integer.parseInt(endNo) - Integer.parseInt(startNo)+1;
					cngObj.setUsedSegmentNo(cngObj.getUsedSegmentNo()+toUpdateAmount);
					if(segAmount == (usedAmount+toUpdateAmount)){
						cngObj.setIsUseUp("1");
					}else{
						cngObj.setIsUseUp("0");
					}
					CardNoGeneratedToUpdate.add(cngObj);
				}
				if(cardNoGeneratedList.size()>1){
					for(int jj=0;jj<cardNoGeneratedList.size();jj++){
						//顺序执行，顺序
						CardNoGenerated cngObj = cardNoGeneratedList.get(jj);
						if(jj==0){
							String db_endNo = cardNoGeneratedList.get(jj).getEndSegmentNo();
							Integer updateAmount = Integer.parseInt(db_endNo) - Integer.parseInt(startNo) + 1;
							Integer usedAmount = cngObj.getUsedSegmentNo();
							Integer segAmount = cngObj.getNum();
							cngObj.setUsedSegmentNo(usedAmount+updateAmount);
							if(segAmount == (segAmount+updateAmount)){
								cngObj.setIsUseUp("1");
							}else{
								cngObj.setIsUseUp("0");
							}
							CardNoGeneratedToUpdate.add(cngObj);
						}else if(jj==(cardNoGeneratedList.size()-1)){
							String db_startNo = cardNoGeneratedList.get(jj).getStartSegmentNo();
							Integer updateAmount = Integer.parseInt(endNo) - Integer.parseInt(db_startNo) + 1;
							Integer segAmount = cngObj.getNum();
							Integer usedAmount = cngObj.getUsedSegmentNo();
							cngObj.setUsedSegmentNo(usedAmount+updateAmount);
							if(segAmount == (segAmount+updateAmount)){
								cngObj.setIsUseUp("1");
							}else{
								cngObj.setIsUseUp("0");
							}
							CardNoGeneratedToUpdate.add(cngObj);
						}else{
							cngObj.setUsedSegmentNo(cngObj.getNum());
							cngObj.setIsUseUp("1");
							CardNoGeneratedToUpdate.add(cngObj);
						}
					}
				}
			}
			//更新卡号库段
			cardNoGerateMapper.batchUpdateAmount(CardNoGeneratedToUpdate);
		}

		// 2.3根据数据库取出的制卡任务编号
	//	List<CardControl> cardInfoList = new ArrayList<CardControl>();
		
	//	cardInfoList = ctm.queryCardInfoByTaskNo(taskList);
	//	logger.debug("cardInfoList==>"+cardInfoList.toString());
		//   2.3.1 遍历list,将卡号和其他信息放入map，任务号是key，卡号是value
//		Map<String,String> taskNoAndCardNo = new HashMap<String,String>();
	//	Map<String,String> citizenNoAndControlID = new HashMap<String,String>();
		
		//组装对应任务和市民卡卡号
	//	String citizenCardNo = "";
	//	for(int ii=0;ii<cardInfoList.size();ii++){
	//		CardControl cardControlObj = cardInfoList.get(ii);
	//		String cardTaskNo = cardControlObj.getCardTaskNo();
	//		String controlId = String.valueOf(cardControlObj.getCardControlId());
	//		String cardNo = cardControlObj.getCardData().getCitizenCardNo();
	//		citizenNoAndControlID.put(cardNo, controlId);
			/*if(taskNoAndCardNo.containsKey(cardTaskNo)){
				citizenCardNo = taskNoAndCardNo.get(cardTaskNo) + "#" + cardControlObj.getCardData().getCitizenCardNo();
			}else{
				citizenCardNo = cardControlObj.getCardData().getCitizenCardNo();
			}*/
			//任务号，对应的卡号
	//		taskNoAndCardNo.put(cardTaskNo, citizenCardNo);
	//	}
	//	logger.debug("申请的任务编号对应卡号的map==>"+taskNoAndCardNo);
	//	logger.debug("申请的卡号对应的控制号map==>"+citizenNoAndControlID);
		//   2.3.2和页面上的map，key是卡号，value 制卡结果做验证
		//   遍历任务编号list，取出每个任务编号对应的卡号，并验证文件卡号对应的制卡结果
		//    如果该任务编号中的制卡结果有失败的，那么falg=0，如果全部成功，则为1
		//    将返回0的制卡任务编号，放入一个list中，1的任务编号，放入另一个list中
			
	    //   2.3.2.3 制卡任务全部成功和部分成功的任务号list
	//	List<String> taskMakeSuccess = new ArrayList<String>();
//		List<String> taskMakeSuccessPartial = new ArrayList<String>();
		
		//   2.3.2.5 制卡成功和失败的卡控制号list
	//	List<String> cardControlIdSuccess = new ArrayList<String>();
	//	List<String> citizenCardNoSuccess = new ArrayList<String>();
	//	List<String> cardControlIdFailure = new ArrayList<String>();
		// 记录每个任务编号，制卡成功的数量
	//	Map<String,Integer> taskAndAmount = new HashMap<String,Integer>();
		
	//	for(int jj=0;jj<taskList.size();jj++){
			
			//   2.3.2.4 制卡成功和失败的卡号list
	//		List<String> cardMakeSuccess = new ArrayList<String>();
	//		List<String> cardMakeFailure = new ArrayList<String>();
			
			//Flag 1 任务全部完成 ，0 部分完成
	//		int flag = 1;
	//		String taskNo = taskList.get(jj);
	//		logger.debug("制卡任务编号["+jj+"]==>"+taskNo);
			//取出制卡任务对应的卡号字符串
	//		String citizenCardNos = taskNoAndCardNo.get(taskNo);
	//		logger.debug("citizenCardNos==>"+citizenCardNos);
	//		String[] citizenCardNoArry = citizenCardNos.split("#");
	//		logger.debug("QJMK==>"+cardResultMap);
	//		for(int kk=0;kk<citizenCardNoArry.length;kk++){
	//			logger.debug("QJMK==>"+citizenCardNoArry[kk]);
	//			String makeResult = cardResultMap.get(citizenCardNoArry[kk]);
	//			logger.debug("makeResult===>"+makeResult);
	//			if("0".equals(makeResult)){
	//				logger.debug("citizenCardNoArry===>"+citizenCardNoArry[kk]);
	//				cardMakeSuccess.add(citizenCardNoArry[kk]);
	//				citizenCardNoSuccess.add(citizenCardNoArry[kk]);
	//				cardControlIdSuccess.add(citizenNoAndControlID.get(citizenCardNoArry[kk]));
					
	//			}
	//			logger.debug("cardMakeSuccess===>"+cardMakeSuccess.toString());
	//			if("1".equals(makeResult)){
	//				cardMakeFailure.add(citizenCardNoArry[kk]);
	//				cardControlIdFailure.add(citizenNoAndControlID.get(citizenCardNoArry[kk]));
	//				flag=0;
	//			}
	//		}
			// 制卡任务肯定是成功的
	/*		if(flag==0){
				taskMakeSuccessPartial.add(taskNo);
			}else{*/
	//			taskMakeSuccess.add(taskNo);
	//		}
	//		logger.debug("每个任务制卡成功的所有卡号==>"+cardMakeSuccess.toString());
	//		logger.debug("制卡失败的所有卡号==>"+cardMakeFailure.toString());
	//		taskAndAmount.put(taskNo, cardMakeSuccess.size());
	//	}
		
		
	//	logger.debug("制卡任务全部成功的编号==>"+taskMakeSuccess.toString());
	//	logger.debug("制卡任务部分成功的编号==>"+taskMakeSuccessPartial.toString());
		
		
	//	logger.debug("制卡成功的所有卡控制号==>"+cardControlIdSuccess.toString());
	//	logger.debug("制卡失败的所有卡控制号==>"+cardControlIdFailure.toString());
	//	logger.debug("制卡任务对应的制卡成功数量map==>"+taskAndAmount);
		
		
		
		/*if(taskMakeSuccessPartial.size()>0){
			int updateStatusFlag = ctm.updatePartialSuccTaskStatus(taskMakeSuccessPartial);
		}*/

		
		
		
		// 3.生成入库记录
		StorageReg storageRegObj = new StorageReg();
		// 3.1 属性的设置
		//   3.1.1 取画面传过来的值
		//鱼洲杰20180731修改以下4行
//		String storageNo = map.get("storageNoByPCR");		
		String totalAmount = map.get("totalAmountByPCR");
		String employeNo = map.get("empNoByPCR");
		String branchNo = map.get("branchNoByPurchaseRgByPCR");
		
		//惠国磊 20180816增加以下 行
		String storageNo = inventoryRecordNoUtil.getStorageNo();
		logger.debug("storageNo==>"+storageNo);
		
		//将画面的值装入返回的map中
		resultMap.put("storageNo", storageNo);
		resultMap.put("totalAmount", totalAmount);
		resultMap.put("branchNo", branchNo);
		
		//当前入库日期
		String curDate = DateAndStampUtil.getCurrentDate();
		logger.debug("入库单号==>"+storageNo);
		logger.debug("入库总数量==>"+totalAmount);
		logger.debug("入库柜员编号==>"+employeNo);
		logger.debug("入库网点编号==>"+branchNo);
		
		//返回的map中的日期变量
		resultMap.put("curDate", curDate);
		// 生成记录
		storageRegObj.setStorageNo(storageNo);
		storageRegObj.setBussinessNo("");
		// 出入库明细号编辑 
		//   查出最大的入库明细号，再进行编辑
		
		storageRegObj.setStorageDetailNo("");
		storageRegObj.setAmount(Integer.parseInt(totalAmount));
		// 01 代表制卡入库
		storageRegObj.setStorageMode("01");
		storageRegObj.setStorageType("0");
		//这里需要将reason再建一个表，入库原因及原因代码
		storageRegObj.setStorageReason("制卡返回入库");
		
		storageRegObj.setStorageDate(curDate);
		storageRegObj.setStorageStatus("1");
		storageRegObj.setRevocationDate("");
		storageRegObj.setRevocationOperatorNo("");
		storageRegObj.setRevocationBranchNo("");
		storageRegObj.setStartNo("");
		storageRegObj.setEndNo("");
		storageRegObj.setSourcePosition("1");
		storageRegObj.setDesPosition("0");
		//这里可以写制卡商代码
		storageRegObj.setSourceBranchNo("制卡商");
		//这里可以写中心库房网点编号
		storageRegObj.setDesBranchNo("中心库房");
		storageRegObj.setIsReceive("");
		storageRegObj.setBothSeqNo("");
		storageRegObj.setDataInMode("1");
		storageRegObj.setOperatorNo(activeUser.getUserNo().toString());
		storageRegObj.setOperateBranchNo(activeUser.getBranchNo());
		storageRegObj.setInputDate(curDate);
		storageRegObj.setRemark("");
		storageRegObj.setRevocationBussinessNo("");
		logger.debug("storageRegObj==>"+storageRegObj);
		srm.insert(storageRegObj);
		
		
		//  4.生成入库明细记录
		//    如果选中多个文件导入
		//       如果这个文件只包含一个任务 ，那么一个任务则是一条明细记录
		//       如果这个文件包含多个任务，多个任务多个记录，
		
		for(int i=0;i<makeCardNoList.size();i++){
			//装载taskNo的lsit 
			List<String> taskNoList = new ArrayList<String>();
			
			
			//通过制卡批号获取对应的任务号数组
			String taskNoToString = taskABatch.get(makeCardNoList.get(i));
			String[] taskNoArray = taskNoToString.split("#");
			if(taskNoArray.length>0){
				for(int k= 0;k<taskNoArray.length;k++){
					taskNoList.add(taskNoArray[k]);
				}
			}
			if(taskNoArray.length==0){
				taskNoList.add(taskNoToString);
			}
			//每个制卡批号，对应的任务
			String detailNo = getDetailNo();
			for(int j=0;j<taskNoList.size();j++){
				String taskNoToInsert = taskNoList.get(j);
				StorageDetail storageDetailObj = new StorageDetail();
				// 4.1属性值的设置
				String branchMakeNo = makeCardNoList.get(i);
				//通过taskAndAmount，获取制卡任务对应的成功返回数量
				Integer successAmount = taskAndAmount.get(taskNoToInsert);
				
				logger.debug("制卡批号==>"+branchMakeNo);
				logger.debug("制卡任务号是==>"+taskNoToInsert);
				logger.debug("制卡任务对应的成功制卡数量==>"+successAmount);
				
				storageDetailObj.setStorageDetailNo(detailNo);
				storageDetailObj.setStorageNo(storageNo);
				storageDetailObj.setBranchMakeNo(branchMakeNo);
				storageDetailObj.setTaskNo(taskNoToInsert);
				storageDetailObj.setDistributeTaskNo("");
				storageDetailObj.setRequestUserNo("");
				storageDetailObj.setItemAttrVal05("");
				storageDetailObj.setAmount(successAmount);
				logger.debug("storageDetailObj==>"+storageDetailObj);
				sdm.insert(storageDetailObj);
				
				//重新计算入库明细号，并追加1
				detailNo = getDetailNoNew(detailNo);
				logger.debug("detailNo==>"+detailNo);
				
			}
		}	
		
		// 5. 生成库存汇总信息
		//    5.1属性设置
		//     库存汇总ID值是建表初期就建立的
		//     在卡产品代码上建立索引，通过代码对应ID值并更新
		logger.debug("网点编号==>"+branchNo);
		//卡产品代码对应的入库数量
		Map<String,Integer> cardPCodeMap = new HashMap<String,Integer>();
		for(int j=0;j<cardPCodeList.size();j++){
			String cardPCodeByStockSum = cardPCodeList.get(j)+"#"+cardStockTypeList.get(j)+"#"+cardPhysicTypeArray[j];
			Integer successAmount = amountListByBtach.get(j);
			
			if(cardPCodeMap.containsKey(cardPCodeByStockSum)){
				successAmount = successAmount + cardPCodeMap.get(cardPCodeByStockSum);
			}
			logger.debug("按产品划分，制卡成功的数量是==>"+successAmount);
			cardPCodeMap.put(cardPCodeByStockSum, successAmount);	
		}
		logger.debug("cardPCodeMap==>"+cardPCodeMap);	
		//查询卡产品code对应的名称
		List<CardProdunctDefinition> cardPObject = cpdm.queryCardNameByCode(cardPCodeList);
		Map<String,String> cardCodeMap = new HashMap<String,String>();
		for(int j=0;j<cardPObject.size();j++){
			String cardCode = cardPObject.get(j).getCardpCode();
			String cardPName = cardPObject.get(j).getCardpName();
			cardCodeMap.put(cardCode, cardPName);
		}
				
		//根据有多少种卡产品进行更新多少条数据
		for(Entry<String,Integer> entry:cardPCodeMap.entrySet()){
			StockSum stockSum = new StockSum();
			stockSum.setBranchNo(branchNo);
			String cardPCodeAndType = entry.getKey();
			String cardPcode = cardPCodeAndType.split("#")[0];
			String type = cardPCodeAndType.split("#")[1];
			String cardPhysicType = cardPCodeAndType.split("#")[2];
			stockSum.setCardpCode(cardPcode);
			stockSum.setCardStockType(type);
			stockSum.setStockPosition("1");
			stockSum.setCardpName(cardCodeMap.get(cardPcode));
			stockSum.setCardPhysicType(cardPhysicType);
			
			
			//现根据卡产品代码，网点编号，stockStatus=1条件查询库中是否有数据，
			//如果没有则插入一条数据，然后再更新
			//如果有，则直接更新
			
			String stockSumID = ssm.queryStockSumNoByCardPCode(stockSum);
			logger.debug("库存汇总ID==>"+stockSumID);
			String stockSumIDToUpdate = null;
			if("".equals(stockSumID) || stockSumID==null){
				//查找库存汇总表中最大的ID号
				String newID = null;
				String maxStockSumID = ssm.queryMaxStockSumID();
				if(!"".equals(maxStockSumID)&&maxStockSumID!=null){
					Integer no = Integer.parseInt(maxStockSumID.substring(4))+1;
					//取得的数字的长度
					int numLength = String.valueOf(no).length();
					//判断取得的数字长度与字段长度，如果小于字段长度，那么说明字段的数字位是以0开头的，需要补位
					int addZero = maxStockSumID.substring(4).length()-numLength;
					if(addZero>0){
						int len = maxStockSumID.substring(4).length();
						newID = "KCHZ"+String.format("%0" + len + "d", no);
					}
					if(addZero==0){
						newID = "KCHZ"+no;
					}
				}else{
					newID = "KCHZ000001";
				}
				
				logger.debug("库存出入库汇总号是==>"+newID);
				
				stockSum.setStockSumId(newID);
				stockSum.setTotalNum(0);
				stockSum.setCurrNum(0);
				stockSum.setRealOutNum(0);
				stockSum.setOutSum(0);
				ssm.insertNewStockInfo(stockSum);
				stockSumIDToUpdate = newID;
			}else{
				stockSumIDToUpdate = stockSumID;
			}
			
			StockSum stockSumObjTemp = ssm.queryStockSumBySumId(stockSumIDToUpdate);
			stockSum.setLastOperator(empNo);
			stockSum.setLastModDate(curDate);
			stockSum.setOperatorAmount(entry.getValue());
			logger.debug("此次入库该产品操作的数量是==>"+stockSum.getOperatorAmount());
			logger.debug("stockSum==>"+stockSum);
			ssm.updateStockSumByIcoming(stockSum);
		}
		
		// 6更新库存汇总明细表（根据制卡任务编号进行分类并插入表中，20180409取消）
        //	    6.1属性设置,
		
		String ID = stockdm.queryMaxDetailId();
		if("".equals(ID)||null==ID){
			ID = "1";
		}
		int id = Integer.parseInt(ID)+1;
		for(int i=0;i<makeCardNoList.size();i++){	
			StockSum stockSum = new StockSum();
			stockSum.setBranchNo(branchNo);
			stockSum.setCardpCode(cardPCodeList.get(i));
			stockSum.setStockPosition("1");
			stockSum.setCardStockType(cardStockTypeList.get(i));
			stockSum.setCardPhysicType(cardPhysicTypeArray[i]);
		//   库存汇总ID，需要查询出来
			String stockSumID = ssm.queryStockSumNoByCardPCode(stockSum);
			StockDetail stockDetail = new StockDetail();
			stockDetail.setStockSumId(stockSumID);
			stockDetail.setStockDetailId(id);
			//制卡返回文件号，这里不需要，可以从入库出库明细中查询
		//	stockDetail.setMakecardReturnNo(makeCardNoList.get(i));
			stockDetail.setItemAttrVal03("");
			stockDetail.setItemAttrVal04("");
			stockDetail.setItemAttrVal05("");
			stockDetail.setAmount(amountListByBtach.get(i));
			stockDetail.setInStockStat("0");
			stockDetail.setLstInNo(storageNo);
			stockDetail.setLstOutNo("");
			stockDetail.setLstInDate(curDate);
			stockDetail.setLstOutDate("");
			stockDetail.setLstInOperator(empNo);
			stockDetail.setLstOutOperator("");
			stockDetail.setFileDate("");
			stockDetail.setFileFlag("");
			
			//对应每个制卡批次，取得任务编号,并且取得每个任务对应的制卡成功数量
			//取得批次号对应的任务编号
			String[] taskNoByBatch = taskABatch.get(makeCardNoList.get(i)).split("#");
			logger.debug("制卡任务号的长度==>"+taskNoByBatch.length);
			for(int j=0;j<taskNoByBatch.length;j++){
				stockDetail.setStockDetailId(id);
				String taskNo = taskNoByBatch[j];
				Integer successAmountByTask = taskAndAmount.get(taskNo);
				logger.debug("successAmountByTask==>"+successAmountByTask);
				stockDetail.setAmount(successAmountByTask);
				stockDetail.setTaskNo(taskNo);
				logger.debug("stockDetail==>"+stockDetail);
				stockdm.insert(stockDetail);
				id++;
			}
		}
		
		
		// 生成pdf文档
		resultMap.put("companyList", companyList);
		resultMap.put("makeCardNoList", makeCardNoList);
		resultMap.put("amountList", amountListByBtach);		
		resultMap.put("credential_type", "storage");
		resultMap.put("title", "采购卡入库清单");
		//装载卡产品
		resultMap.put("cardPNameList", cardPNameList);
		
		createStoragePDF(resultMap);
		
		// 7 移动制卡返回文件到指定文件夹下
		for(int x=0;x<makeCardNoList.size();x++){
			String successTargetPath = RESPONSESUCCESS_PATH+File.separator+companyList.get(x);
			String fileNameToString = map.get("makeCardFileName");
			String[] fileNameArray = fileNameToString.split("\\$");
			logger.debug("文件个数==>"+fileNameArray.length);
	//		for(int y=0;y<fileNameArray.length;y++){
	//			String sourcePath = FileUtil.responseFile+File.separator+companyList.get(x)+File.separator+fileNameArray[y]+".txt";
				String sourcePath = INCOMING_PATH+File.separator+companyList.get(x)+File.separator+fileNameArray[x]+".txt";
				logger.debug("要移动的文件路径==>"+sourcePath);
				FileUtil.moveTotherFolders(sourcePath,successTargetPath);
	//		}	
		}
		
		Map<String,Object> rMap = new HashMap<String,Object>();
		rMap.put("ipAddress", IP_ADDRESS);
		rMap.put("credential_type", "storage");
		rMap.put("storageNo", storageNo);
		
		logger.debug("返回的Map是==>"+rMap);
		
		return rMap;
	}
	
	/**
	 * 库存明细号加1
	 * @param detailNo
	 * @return
	 */
	private String getDetailNoNew(String detailNo) {
		String detailNoReturn = null;
		Integer dno = Integer.parseInt(detailNo.substring(2))+1;
		//取得的数字的长度
		int numLength = String.valueOf(dno).length();
		//判断取得的数字长度与字段长度，如果小于字段长度，那么说明字段的数字位是以0开头的，需要补位
		int addZero = detailNo.substring(2).length()-numLength;
		if(addZero>0){
			int len = detailNo.substring(2).length();
			detailNoReturn = "MX"+String.format("%0" + len + "d", dno);
		}
		if(addZero==0){
			detailNoReturn = "MX"+dno;
		}
		return detailNoReturn;
	}

	/**
	 * 编号：1-9-2
	 * 功能：生成PDF文档
	 * @param rMap
	 */
	@SystemServiceLog(description = "生成PDF文档")
	public void createStoragePDF(Map<String, Object> rMap) {
		rMap.put("credential_type", "storage");
		rMap.put("credentialPath",CREDENCIAL_PATH);
		TempletTicket storageTest = new TempletTicket();
		storageTest.createStoragePDF(rMap);
	}	
	
	/**
	 * 编号：2-1-1
	 * 功能：查询可配送的任务信息
	 * @param map
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@SystemServiceLog(description = "查询可配送的任务信息")
	public DwzPage<CardTask> queryTaskInfo(Map<String,String> map,Integer currentPage, Integer numPerPage) {
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		
		//取得前画面的值
		String cardPCode = map.get("cardPCode");
		String branchNo = map.get("branchNo");
		String taskNo = map.get("taskNo");
		String taskName = map.get("taskName");
		logger.debug("配送查询画面的cardPName==>"+cardPCode);
		logger.debug("配送查询画面的branchNo==>"+branchNo);
		logger.debug("配送查询画面的taskNo==>"+taskNo);
		logger.debug("配送查询画面的taskName==>"+taskName);
		//可配送的任务信息列表
		Integer startLine = (currentPage-1)*numPerPage;
		//鱼洲杰修改
		List<CardTask> cardTaskList = ctm.queryDistributionByTask(cardPCode, branchNo, taskNo, taskName,activeUser.getBranchNo(),startLine,numPerPage);
		//页面列表信息
		//鱼洲杰修改
		Integer totalCount =ctm.queryDistributionByTaskNumber(cardPCode, branchNo, taskNo, taskName,activeUser.getBranchNo());
		DwzPage<CardTask> dp = new DwzPage<CardTask>(currentPage, numPerPage ,totalCount);
		dp.setList(cardTaskList);
		return dp;
	}
	
	/**
	 * 编号：2-2-1
	 * 功能：查询出所有可配送的信息
	 * @param checkedInfo
	 * @return
	 */
	@SystemServiceLog(description = "查询出所有可配送的信息")
	public Map<String, Object> getEditDistributionMap(String checkedInfo) {
		logger.debug("checkedInfo==>"+checkedInfo);
		//产品代码的Lisy
		List<String> cardPCodeList= new ArrayList<String>();
		//产品名称的List
		List<String> cardPNameList= new ArrayList<String>();
		//产品名称的Map
		Map<String,String> cardPNameMap= new HashMap<String,String>();
		//产品数量的Map
		Map<String,String> cardAmountMap= new HashMap<String,String>();
		//任务编号的List
		List<String> taskNoList = new ArrayList<String>();
		//制卡编号list
		List<String> branchMakeNoList = new ArrayList<String>();
		//制卡商List
		List<String> companyList = new ArrayList<String>();
		//卡物理类型
		List<String> cardPhysicTypeList = new ArrayList<String>();
		
		
		//返回的map对象
		Map<String,Object> map = new HashMap<String,Object>();
		//配送的数量
		int distributeAmount = 0;
		//判断checkedInfo是否是多条信息
		String[] checkedInfos = checkedInfo.split("\\$");
		int len = checkedInfos.length;
		logger.debug("len==>"+len);

		//获取当前日期
		String currentDate = DateAndStampUtil.getCurrentDate();
		//只选中了一条数据
		if(len==0){
			String[] checkedInfoArray = checkedInfo.split("#");
			map.put("applyBranch", checkedInfoArray[1]);
			map.put("applyBranchNo", checkedInfoArray[11]);
			distributeAmount = Integer.parseInt(checkedInfoArray[5]);
			taskNoList.add(checkedInfoArray[2]);
			cardPhysicTypeList.add(checkedInfoArray[3].substring(3, 4));
			cardPCodeList.add(checkedInfoArray[8]);
			cardPNameList.add(checkedInfoArray[0]);
			branchMakeNoList.add(checkedInfoArray[9]);
			companyList.add(checkedInfoArray[10]);
			cardPNameMap.put(checkedInfoArray[2], checkedInfoArray[0]);
			cardAmountMap.put(checkedInfoArray[2], checkedInfoArray[5]);
			
		}
		//选中了多条数据
		if(len>0){
			map.put("applyBranch", checkedInfos[0].split("#")[1]);
			map.put("applyBranchNo", checkedInfos[0].split("#")[11]);
			for(int i=0;i<len;i++){
				logger.debug("被分解的字符串==>"+checkedInfos[i]);
				String[] checkedInfoArray = checkedInfos[i].split("#");
				distributeAmount = distributeAmount + Integer.parseInt(checkedInfoArray[5]);
				taskNoList.add(checkedInfoArray[2]);
				cardPCodeList.add(checkedInfoArray[8]);
				cardPNameList.add(checkedInfoArray[0]);
				cardPhysicTypeList.add(checkedInfoArray[3].substring(3, 4));
				branchMakeNoList.add(checkedInfoArray[9]);
				companyList.add(checkedInfoArray[10]);
				cardPNameMap.put(checkedInfoArray[2], checkedInfoArray[0]);
				cardAmountMap.put(checkedInfoArray[2], checkedInfoArray[5]);
			}
			
		}
		
		logger.debug("taskNoList==>"+taskNoList);
		map.put("distributeAmount", String.valueOf(distributeAmount));
		map.put("taskNoList", taskNoList);
		map.put("cardPCodeList", cardPCodeList);
		map.put("cardPNameList", cardPNameList);
		map.put("cardPNameMap", cardPNameMap);
		map.put("cardAmountMap", cardAmountMap);
		map.put("distributeDate", currentDate);
		map.put("branchMakeNoList", branchMakeNoList);
		map.put("companyList", companyList);
		map.put("cardPhysicTypeList", cardPhysicTypeList);
		//获取出库单号
//		String storageNo = inventoryRecordNoUtil.getStorageNo();
//		map.put("storageNo", storageNo);
		//获取配送任务号
//		String distributeTaskNo = inventoryRecordNoUtil.getDistributeTaskNo();
//		map.put("distributeTaskNo", distributeTaskNo);
		logger.debug("编辑后的map==>"+map);
		return map;
	}
	
	
	/**
	 * 编号：3-1-1
	 * 功能：查询配送任务信息，并返回
	 */
	@SystemServiceLog(description = "查询配送任务信息并返回")
	public DwzPage<StorageRegRecVo> getCardReceiving(Map<String, String> map, Integer pageNum, Integer numPerPage) {
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		
		String distributeTaskNo = map.get("distributeTaskNo");
		logger.debug("画面的distributeTaskNo==>"+distributeTaskNo);
		String applyBatchNo = activeUser.getBranchNo();
		//查询出的信息：
		// 1.卡产品名称 2.接收网点 3. 申请数量 4. 配送数量 ,5. 配送日期 ,6.制卡任务编号   没有申请批次号
		Integer startLine = (pageNum-1)*numPerPage;
		List<StorageRegRecVo> srrv = srm.queryReceiveDistributeInfo(distributeTaskNo,applyBatchNo,startLine,numPerPage);
		//根据上述查询出的任务号，查出申请批次号( 一对一 )
		
		//  任务号和批次号对应的map,key是任务号
		Map<String,Object> applyBatchAndTaskNo = new HashMap<String,Object>();
		 
		//  任务号列表
		List<String> taskNoList = new ArrayList<String>();
		
		//新建列表
		List<StorageRegRecVo> storageVoNewList = new ArrayList<StorageRegRecVo>();
		//鱼洲杰修改
		int totalCount=0;
		// 20180917 惠国磊修改 去除网点的判断(中心库也能配送中心库)，后面再讨论
	//	if(!activeUser.getBranchNo().equals("10000000")){
		if(srrv.size()>0){
			for(int i=0;i<srrv.size();i++){
				StorageRegRecVo storageVoObj = srrv.get(i);
				String taskNo = storageVoObj.getTaskNo();
				taskNoList.add(taskNo);
			}
			//  查询任务号和批次号
			List<StorageRegRecVo> storageVoList = srm.queryApplyNoByTaskNo(taskNoList);
			
			for(int j=0;j<storageVoList.size();j++){
				StorageRegRecVo storageVoObj = storageVoList.get(j);
				if("".equals(storageVoObj.getApplyBatchNo())||storageVoObj.getApplyBatchNo()==null){
					applyBatchAndTaskNo.put(storageVoObj.getTaskNo(), "此为空白卡，无批次号！");
				}else{
					applyBatchAndTaskNo.put(storageVoObj.getTaskNo(), storageVoObj.getApplyBatchNo());
				}
				
			}
			logger.debug("任务号和批次号对应的map==>"+applyBatchAndTaskNo);
			
			for(int m=0;m<srrv.size();m++){
				StorageRegRecVo storageVoObj = srrv.get(m);
				String taskNo = storageVoObj.getTaskNo();
				storageVoObj.setApplyBatchNo((String)applyBatchAndTaskNo.get(taskNo));
				logger.debug("StorageRegVo==>"+storageVoObj.toString());
				storageVoNewList.add(storageVoObj);
			}
			totalCount=srrv.size();
		}	
			
	//	}
		//分页处理
		DwzPage<StorageRegRecVo> dp = new DwzPage<StorageRegRecVo>(pageNum, numPerPage ,totalCount);
		ListPageUtil<StorageRegRecVo> listPageUtil = new ListPageUtil<>(storageVoNewList,pageNum, numPerPage);
		List<StorageRegRecVo> pagedList = listPageUtil.getPagedList();
		dp.setList(pagedList);
		logger.debug("配送信息==>"+pagedList);
		
		return dp;
	}
	
	/**
	 * 编号：3-2-1
	 * 功能：入库登记，数据库操作（1.出入库记录表，2.出入库明细，3.库存汇总，
	 * 4.库存汇总明细，5.卡控制，6.，7.，8）
	 * @throws ApplicationException 
	 */
	@SystemServiceLog(description = "库存汇总明细")
	@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
	public Map<String,Object> CardReceivingRegist(String checkedeParam) throws InventoryException {
		//20180528 惠国磊  以下1行
		logger.debug("controller传递过来的参数==>"+checkedeParam);
		//返回的打印用参数map
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		
		
		//制卡任务列表
		List<String> taskNoList = new ArrayList<String>();
		//任务对应的卡物理类型
		List<String> cardPhysicTypeList = new ArrayList<String>();
		//制卡任务返回的数量
		List<Integer> amountList = new ArrayList<Integer>();
		//卡产品名称列表
		List<String> cardPNameList = new ArrayList<String>();
		//无重复的卡产品代码列表
		List<String> cardPCodeList = new ArrayList<String>();
		//重复的卡产品代码列表
		List<String> cardPCodeList2 = new ArrayList<String>();
		//申请批次号信息
		List<String> applyBatchNoList = new ArrayList<String>();
		//每个卡产品对应的制卡任务
		Map<String,String> cardCodeAndTypeTaskNo = new HashMap<String,String>();
		//每个卡产品，对应的数量
		Map<String,Integer> cardCodeAndTypeAmount = new HashMap<String,Integer>();
		//每个任务对应的卡片数量
		Map<String,Integer> taskNoAndAmount = new HashMap<String,Integer>();
		//每个任务对应的库存类型
		Map<String,String> taskNoAndType = new HashMap<String,String>();
		
		String desBranchNo = null;
		String sourceStorageNo = null;
		String distributeTaskNo = null;
		int totalAmount = 0;
		//解析传递过来的参数
		String[] checkedeParamArray = checkedeParam.split("\\$");
		for(int j=0;j<checkedeParamArray.length;j++){
			String[] paramArray = checkedeParamArray[j].split("#");
			String taskNo = paramArray[0];
			String cardPCode = paramArray[1];
			String cardPName = paramArray[2];
			desBranchNo = paramArray[3];
			String amount = paramArray[4];
			Integer cardPCodeAmount = null;
			sourceStorageNo = paramArray[5];
			String applyBtachNo = paramArray[6];
			String physicType = paramArray[paramArray.length-1];
			distributeTaskNo = paramArray[7];
			applyBatchNoList.add(applyBtachNo);
			taskNoList.add(taskNo);
			cardPhysicTypeList.add(physicType);
			amountList.add(Integer.parseInt(amount));
			cardPCodeList2.add(cardPCode);
			cardPNameList.add(cardPName);
			taskNoAndAmount.put(taskNo, Integer.parseInt(amount));
			logger.debug("taskNo===>"+taskNo);
			logger.debug("cardPcode==>"+cardPCode);
			totalAmount = totalAmount + Integer.parseInt(amount);
		}
		
		//查询每个任务对应制卡文件，制卡文件对应成品卡和空白卡
		List<CardTask> taskObjjList = ctm.queryCardPCodeByTaskNo(taskNoList);
		for(int i=0;i<taskObjjList.size();i++){
			String taskType = taskObjjList.get(i).getTaskType();
			String taskNo = taskObjjList.get(i).getCardTaskNo();
			if("1".equals(taskType)){
				taskNoAndType.put(taskNo, "2");
			}
			if("2".equals(taskType)){
				taskNoAndType.put(taskNo, "1");
			}
		}
		
		//装配卡产品和任务分类与数量的map
		
		for(int j=0;j<taskNoList.size();j++){
			String taskNo = taskNoList.get(j);
			String taskNos = null;
			String cardPCodeAndType = cardPCodeList2.get(j)+"#"+taskNoAndType.get(taskNo)+"#"+cardPhysicTypeList.get(j);
			Integer cardCodeAndTypeAmounts = 0 ;
			if(cardCodeAndTypeAmount.containsKey(cardPCodeAndType)){
				cardCodeAndTypeAmounts = cardCodeAndTypeAmount.get(cardPCodeAndType) + amountList.get(j);
				taskNos = cardCodeAndTypeTaskNo.get(cardPCodeAndType)+"#"+taskNo;
			}else{
				cardCodeAndTypeAmounts =  amountList.get(j);
				taskNos = taskNo;
			}
			cardCodeAndTypeAmount.put(cardPCodeAndType, cardCodeAndTypeAmounts);
			cardCodeAndTypeTaskNo.put(cardPCodeAndType, taskNo);
		}
		
		
		logger.debug("taskNoAndType==>"+taskNoAndType);
		logger.debug("cardCodeAndTypeAmount==>"+cardCodeAndTypeAmount);
		logger.debug("taskNoAndAmount==>"+taskNoAndAmount);
		logger.debug("cardCodeAndTaskNo==>"+cardCodeAndTypeTaskNo);
		logger.debug("cardPCodeList的大小==>"+cardPCodeList.size());
		
		
		//1.更新接收的出库单号的记录为  已接收
		logger.debug("sourceStorageNo==>"+sourceStorageNo);
		// 1.1 更新前，检查是否已经接收，如果已经接收，提示错误信息
		String reveiveFlag = srm.queryIsReceiveByStorageNo(sourceStorageNo);
		if("1".equals(reveiveFlag)){
			//临时抛出错误
			throw new InventoryException("信息有误,请返回重新刷新页面后继续操作！");
		}
		srm.updateStorageNoByDistribute(sourceStorageNo);
		
		//2.生成出入库记录
		//  2.1生成出入库单号
		String storageNo = inventoryRecordNoUtil.getStorageNo();
		logger.debug("storageNo==>"+storageNo);
		StorageReg sr=new StorageReg();
		sr.setStorageNo(storageNo);
		sr.setBussinessNo("");
		sr.setStorageDetailNo("");
		sr.setAmount(totalAmount);
		//02：接收中心库的制卡配送
		sr.setStorageMode("02");
		sr.setStorageType("0");
		sr.setStorageReason("网点接收配送");
		sr.setStorageDate(DateAndStampUtil.getCurrentDate());
		sr.setRevocationDate("");
		sr.setRevocationOperatorNo("");
		sr.setRevocationBranchNo("");
		sr.setStartNo("");
		sr.setEndNo("");
		sr.setStorageStatus("1");
		sr.setSourcePosition("0");
		sr.setDesPosition("2");
		//这边先写死，来源网点,中心库
		sr.setSourceBranchNo("中心库");
		sr.setDesBranchNo(activeUser.getBranchNo());
		sr.setIsReceive("");
		sr.setBothSeqNo("");
		sr.setDataInMode("0");
		sr.setOperatorNo(activeUser.getUserNo().toString());
		sr.setOperateBranchNo(activeUser.getBranchNo());
		sr.setInputDate(DateAndStampUtil.getCurrentDate());
		sr.setRemark("");
		sr.setRevocationBussinessNo("");
		logger.debug("sr==>"+sr.toString());
		srm.insert(sr);//插入出入库登记表

		
		
		//3.生成出入库明细记录
		String detailNo = getDetailNo();
		for(int i=0;i<taskNoList.size();i++){
			StorageDetail sd=new StorageDetail();
			
			sd.setStorageDetailNo(detailNo);
			sd.setStorageNo(storageNo);
			sd.setDistributeTaskNo(distributeTaskNo);
			sd.setAmount(amountList.get(i));
			sd.setTaskNo(taskNoList.get(i));
			logger.debug("sd["+i+"]==>"+sd.toString());
			sdm.insert(sd);//更新出入库明细表
			
			//重新计算入库明细号，并追加1
			detailNo = getDetailNoNew(detailNo);
			logger.debug("detailNo==>"+detailNo);
		}
		
		//4.更新库存汇总表
		String ID = stockdm.queryMaxDetailId();
		if("".equals(ID)||null==ID){
				ID = "1";
		}
		int id = Integer.parseInt(ID)+1;
		
		Set<Map.Entry<String,Integer>> entrySet = cardCodeAndTypeAmount.entrySet();
		
		for(Entry<String,Integer> entry:entrySet){
			StockSum ss = new StockSum();
			String[] cardPCodeAndType = entry.getKey().split("#");
			String cardPCode = cardPCodeAndType[0];
			String stockType = cardPCodeAndType[1];
			String physicType = cardPCodeAndType[2];
			ss.setBranchNo(activeUser.getBranchNo());
			//鱼洲杰修改
			ss.setCardpCode(cardPCode);
			ss.setCardStockType(stockType);
			ss.setCardPhysicType(physicType);
			//这边的卡产品名称需要修改
			//前面已经有list了
			ss.setCardpName(cpdm.queryCardPCode(cardPCode).getCardpName());
			ss.setStockPosition("2");
			
			//现根据卡产品代码，网点编号，stockStatus=1条件查询库中是否有数据，
			//如果没有则插入一条数据，然后再更新
			//如果有，则直接更新
			
			String stockSumID = ssm.queryStockSumNoByCardPCode(ss);
			logger.debug("库存汇总ID==>"+stockSumID);
			String stockSumIDToUpdate = null;
			if("".equals(stockSumID) || stockSumID==null){
				//查找库存汇总表中最大的ID号
				String newID = null;
				String maxStockSumID = ssm.queryMaxStockSumID();
				Integer no = Integer.parseInt(maxStockSumID.substring(4))+1;
				//取得的数字的长度
				int numLength = String.valueOf(no).length();
				//判断取得的数字长度与字段长度，如果小于字段长度，那么说明字段的数字位是以0开头的，需要补位
				int addZero = maxStockSumID.substring(4).length()-numLength;
				if(addZero>0){
					int len = maxStockSumID.substring(4).length();
					newID = "KCHZ"+String.format("%0" + len + "d", no);
				}
				if(addZero==0){
					newID = "KCHZ"+no;
				}
				logger.debug("库存出入库汇总号是==>"+newID);
				ss.setStockSumId(newID);
				ss.setTotalNum(0);
				ss.setCurrNum(0);
				ss.setRealOutNum(0);
				ss.setOutSum(0);
				ssm.insertNewStockInfo(ss);
				stockSumIDToUpdate = newID;
			}else{

				stockSumIDToUpdate = stockSumID;
			}
			StockSum stockSumObjTemp = ssm.queryStockSumBySumId(stockSumIDToUpdate);
			ss.setLastOperator(activeUser.getUserNo().toString());
			ss.setLastModDate(DateAndStampUtil.getCurrentDate());
			int cardAmount = entry.getValue();
			logger.debug("卡产品数量==>"+cardAmount);
			ss.setOperatorAmount(cardAmount);
			logger.debug("ss==>"+ss.toString());
			ssm.updateStockSumByIcoming(ss);
			
		//   库存汇总ID，需要查询出来
			String stockSumid = ssm.queryStockSumNoByCardPCode(ss);
			
			
			StockDetail stockDetail = new StockDetail();
			stockDetail.setStockSumId(stockSumid);
			
			
		//制卡返回文件号，这里不需要，可以从入库出库明细中查询
		//	stockDetail.setMakecardReturnNo(makeCardNoList.get(i));
			stockDetail.setItemAttrVal03("");
			stockDetail.setItemAttrVal04("");
			stockDetail.setItemAttrVal05("");
			
			stockDetail.setInStockStat("0");
			stockDetail.setLstInNo(storageNo);
			stockDetail.setLstOutNo("");
			stockDetail.setLstInDate(DateAndStampUtil.getCurrentDate());
			stockDetail.setLstOutDate("");
			stockDetail.setLstInOperator(activeUser.getUserNo().toString());
			stockDetail.setLstOutOperator("");
			stockDetail.setFileDate("");
			stockDetail.setFileFlag("");
			
			//设置任务号和数量
			String taskNoArray = cardCodeAndTypeTaskNo.get(entry.getKey());
			String[] taskNos = taskNoArray.split("#");
			for(int i=0;i<taskNos.length;i++){
				String taskNo = taskNos[i];
				logger.debug("taskno["+i+"]==>"+taskNo);
				stockDetail.setTaskNo(taskNo);
				stockDetail.setStockDetailId(id);
				stockDetail.setAmount(taskNoAndAmount.get(taskNo));
				logger.debug("stockDetail===>"+stockDetail.toString());
				stockdm.insert(stockDetail);
				id++;
			}
			
			
		}
		
		
		
		//6.卡过程表
		String cardPosition = "9";
		List<String> citizenCardNoList = cdm.queryCitizenCardNoByDistributeOfCenter(taskNoList,cardPosition);
		//卡过程表
		//查询出卡号
		Date currentDate = new Date();
		List<CardManage> cardMagList = new ArrayList<CardManage>();
		List<CardControl> cardControlObjList = new ArrayList<CardControl>();
		for(int i=0;i<citizenCardNoList.size();i++){
			CardManage cme = new CardManage();
			String currProcId = UUID.randomUUID().toString().replace("-", "");
			cme.setProcessId(currProcId);
			cme.setApplyBranch(activeUser.getBranchName());
			cme.setApplyBranchNo(activeUser.getBranchNo());
			cme.setApplyDate(new Date());
			cme.setApplyTellerNo(activeUser.getUserNo().toString());
			cme.setBusinessNo("");
			cme.setProcessCode(CardContants.CARD_PROC_RECV);
			cme.setProcessName("网点接收");
			cme.setCitizenCardNo(citizenCardNoList.get(i));
			cme.setCardPosition(CardContants.CARD_POSITION_NET_DOT);
			cme.setCardStatus(CardContants.CARD_STATE_DISABLED);
		//	cme.setApplyWay("");// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
			cardMagList.add(cme);
			CardControl cardControlObj = cardControlMap.queryCardControlByCitizenCardNo(citizenCardNoList.get(i));
			cardControlObj.setCardPosition("2");
			cardControlObj.setCurrProcId(currProcId);
			cardControlObj.setLastDate(currentDate);
			cardControlObj.setLastOperator(activeUser.getUserNo().toString());
			cardControlObj.setClaimStatus("08");
			cardControlObjList.add(cardControlObj);
		}
		cmm.batchInsert(cardMagList);
		
		
		// 5.更新卡控制表
		cardControlMap.updateCardControlByReceive(cardControlObjList);
		
		//入库号
		resultMap.put("storageNo", storageNo);
		//网点号
		resultMap.put("branchNo", desBranchNo);
		//入库总数量(因为这里是只选择一项，数量暂时这么编辑，后期需要改正)
		resultMap.put("totalAmount", String.valueOf(totalAmount));
		//入库日期
		resultMap.put("curDate", DateAndStampUtil.getCurrentDate());
		//清单明细抬头
		resultMap.put("title", "网点接收入库清单");
		//卡产品名称列表
		resultMap.put("cardPNameList", cardPNameList);
		//制卡批号列表
		resultMap.put("makeCardNoList", applyBatchNoList);
		//制卡商名称列表
		resultMap.put("companyList", "");
		//每个批号的数量列表
		resultMap.put("amountList", amountList);
		//凭证类型
		resultMap.put("credential_type", "storage");

		
		//生成预览清单
		createStoragePDF(resultMap);
		Map<String,Object> rMap = new HashMap<String,Object>();
		rMap.put("ipAddress", IP_ADDRESS);
		rMap.put("storageNo", storageNo);
		rMap.put("title", "网点接收入库清单");
		rMap.put("credential_type", "storage");
		
		return rMap;
	}
	
	/**
	 * 编号：4-1-1
	 * 功能：查询出入库的信息
	 * @throws InventoryException 
	 */
	@SystemServiceLog(description = "查询出入库信息")
	public DwzPage<StorageRegRecVo> queryAllStorageRegs(Map<String, String> map, Integer pageNum, Integer numPerPage) throws Exception {
		String storageNo = map.get("storageNo");
		String storageMode = map.get("storageMode");
		String storageDateFrom = map.get("storageDateFrom");
		String storageDateTo = map.get("storageDateTo");
		String branchNo = map.get("branchNo");
		logger.debug("画面的storageNo==>"+storageNo);
		logger.debug("画面的storageMode==>"+storageMode);
		logger.debug("入库时间起==>"+storageDateFrom);
		logger.debug("入库时间止==>"+storageDateTo);
		logger.debug("入库网点编号==>"+branchNo);
		logger.debug("pageNum==>"+pageNum);
		logger.debug("numPerPage==>"+numPerPage);
		Integer startLine = (pageNum-1)*numPerPage;
		//20180928鱼洲杰修改以下行
		Integer endLine = numPerPage;
		List<StorageRegRecVo> srrv = new ArrayList<StorageRegRecVo>();

		srrv = srm.queryAllStorageReg(storageNo, storageMode, storageDateFrom, storageDateTo,branchNo,startLine,endLine);
	
		logger.debug("queryAllStorageRegs==>"+srrv.toString());
		//查询总的数量
		Integer totalCount = srm.countAllStorageReg(storageNo, storageMode, storageDateFrom, storageDateTo,branchNo);
		logger.debug("totalCount==>"+totalCount);
		//分页处理
		DwzPage<StorageRegRecVo> dp = new DwzPage<StorageRegRecVo>(pageNum, numPerPage ,totalCount);
		dp.setList(srrv);
		return dp;
	}
	
	/**
	 * 编号:4-2-1
	 * 功能：入库撤销（出库撤销可以参照）
	 * @throws ApplicationException 
	 */
	@SystemServiceLog(description = "出入库撤销")
	@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
	public void incomingCancelSubmit(String[] itemArrays) throws InventoryException{
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		
		//废卡文件名
		String  rejectTaskFileName = null;
		//入库地址
		String stockPosition = null;
		//解析出入库流水号
		String storageNo = itemArrays[0];
		//解析出入库模式
		String storageMode = itemArrays[1];
		//解析出入库数量
		String storageAmount = itemArrays[5];
		//解析出入库网点编号
		String branchNo = itemArrays[2];
		//当前日期
		String currentDate = DateAndStampUtil.getCurrentDate();
		
		//20181008 huiguolei 增加下面1行
		String blankTaskFilePath = null;
		//入库方式数组
		String[] incomingArray = {"01","02","03","04","05"};
		//出库方式数组
		String[] outArray = {"11","13","14","15"};
		//设定撤销时需要更新的各个表的共同的变量
		//1.卡位置，卡申领状态
		String cardPosition = null;
		String claimStatus = null;
		if("01".equals(storageMode)){
			cardPosition = "0";
			claimStatus = "04";
		}else if("02".equals(storageMode)){
			cardPosition = "9";
			claimStatus = "07";
		}else if("03".equals(storageMode)){
			cardPosition = "9";
		}else if("04".equals(storageMode)){
			cardPosition = "9";
		}else if("05".equals(storageMode)){
			//盘盈入库撤销时，卡位置，全部设置成9.
			cardPosition = "9";
		}else if("11".equals(storageMode)){
			cardPosition = "1";
			claimStatus = "06";
		}else if("13".equals(storageMode)){
			cardPosition = "2";
			claimStatus = "08";
        }else if("14".equals(storageMode)){
			//盘亏出库撤销时，卡位置，全部设置成在库
        	//如果是中心库那么设置成1，如果是网点设置成2
        	if("10000000".equals(branchNo)){
        		cardPosition = "1";
        	}else{
        		cardPosition = "2";
        	}	
		}else if("15".equals(storageMode)) {
			cardPosition = "2";
		}
		
		//2.移动文件路径：3.原路径 4.目标路径 
		//2.1 根路径
		String sourceBasePath = "";
		String targeBasetPath = "";
		if("01".equals(storageMode)){
			sourceBasePath = RESPONSESUCCESS_PATH;
			targeBasetPath = INCOMING_PATH;
		}else if("03".equals(storageMode)||"04".equals(storageMode)){
			sourceBasePath = BLANK_REJECT_TASK_RECEIVED_PATH;
			targeBasetPath = BLANK_REJECT_TASK_PATH;
		}else if("13".equals(storageMode)||"15".equals(storageMode)){
			sourceBasePath = BLANK_REJECT_TASK_PATH;
		}
		
		//1.更新出入库登记
		String status = srm.queryStorageStatusByStorageNo(storageNo);
		if("2".equals(status)){
			//临时抛出的错误
			throw new InventoryException("信息有误,请返回并刷新页面后继续操作！");
		}
		String curEmpNo = activeUser.getUserNo().toString();
		String curBranchNo = activeUser.getBranchNo();
		//添加出入库撤销标志
		srm.updateStorageRegByCancel(storageNo,curEmpNo,curBranchNo);
		//接收标志清零
		if("03".equals(storageMode)||"02".equals(storageMode)||"04".equals(storageMode)){
			srm.updateStorageReceiveByCancel(storageNo);
		}
		
		//2.更新库存汇总表
		//2.1 根据入库流水号查询出库存汇总ID
		List<StockDetail> stockSumList = new ArrayList<StockDetail>();
		if(ArrayUtils.contains(incomingArray,storageMode)){
			String column = "LST_IN_NO";
			stockSumList = stockdm.queryStockDetailByLstOutNoAndSum(storageNo,column,"0");
		}else if(ArrayUtils.contains(outArray,storageMode)){
			String column = "LST_OUT_NO";
			stockSumList = stockdm.queryStockDetailByLstOutNoAndSum(storageNo, column,"1");
		}
		
		
		for(int i=0;i<stockSumList.size();i++){
			StockSum ssobj = new StockSum();
			//2.2 更新前，锁死
			Integer operatorAmount = stockSumList.get(i).getAmount();
			logger.debug("operatorAmount==>"+operatorAmount);
			String stockSumId = stockSumList.get(i).getStockSumId();
			ssobj.setOperatorAmount(operatorAmount);
			ssobj.setLastModDate(currentDate);
			ssobj.setLastOperator(curEmpNo);
			ssobj.setStockSumId(stockSumId);
			StockSum stocksumObj = ssm.queryStockSumBySumId(stockSumId);
			//2.3 更新数量
			if(ArrayUtils.contains(incomingArray,storageMode)){
				ssm.updateStockSumByCancelIncoming(ssobj);
			}
			if(ArrayUtils.contains(outArray,storageMode)){
				ssm.updateStockSumByOutCancel(ssobj);
			}
			
		}
		
		List<CardBatch> cardBatchList =	cbm.queryCardBatchByStorageNo(storageNo);
		
		List<StorageDetail> storageDetailList = sdm.queryStorageObjByStorageNo(storageNo);
		List<String> taskNoList = new ArrayList<String>();
		List<String> makeBatchNoList = new ArrayList<String>();
		List<String> distributeTaskNoList = new ArrayList<String>();
		List<CardControl> cardControlList = new ArrayList<CardControl>();
		List<String> cardControlIdList = new ArrayList<String>();
		for(int i=0;i<storageDetailList.size();i++){
			StorageDetail sdobj = storageDetailList.get(i);
			if("01".equals(storageMode)){
				makeBatchNoList.add(sdobj.getBranchMakeNo());
				taskNoList.add(sdobj.getTaskNo());
				//通过taskNolist查找controlId
			}else if("02".equals(storageMode)||"11".equals(storageMode)){
				taskNoList.add(sdobj.getTaskNo());
			}else if("03".equals(storageMode)||"04".equals(storageMode)||"13".equals(storageMode)||"15".equals(storageMode)){
				distributeTaskNoList.add(sdobj.getDistributeTaskNo());
			}
		}
		
		makeBatchNoList = listUtil.listToSet(makeBatchNoList);
		taskNoList = listUtil.listToSet(taskNoList);
		distributeTaskNoList = listUtil.listToSet(distributeTaskNoList);
		
		if("01".equals(storageMode)||"02".equals(storageMode)||"11".equals(storageMode)){
			cardControlList = ctm.queryCardInfoByTaskNo(taskNoList);
		}
		if("04".equals(storageMode)||"03".equals(storageMode)||"13".equals(storageMode)||"15".equals(storageMode)){
			cardControlList = parseFile.parseDistributeTaskFile(distributeTaskNoList, sourceBasePath);
		}
		
		//插入卡管理表
		
		for(int j=0;j<cardControlList.size();j++){
			logger.debug("controlId"+j+"==>"+cardControlList.get(j).getCardControlId());
			cardControlIdList.add(String.valueOf(cardControlList.get(j).getCardControlId()));		
		}
		List<CardData> cardDataObjList = cdm.queryCardDataByCardControlIdList(cardControlIdList);
		//卡过程表
		List<CardManage> cardMagList = new ArrayList<CardManage>();
		List<CardControl> cardControlObjList = new ArrayList<CardControl>();
		for(int i=0;i<cardDataObjList.size();i++){
			CardManage cme = new CardManage();
			CardControl cardControlObj = cardControlMap.queryCardControlByCitizenCardNo(cardDataObjList.get(i).getCitizenCardNo());
			String currProcId = UUID.randomUUID().toString().replace("-", "");
			cme.setProcessId(currProcId);
			cme.setApplyBranchNo(branchNo);
			cme.setApplyDate(new Date());
			cme.setApplyTellerNo(curEmpNo);
			cme.setBusinessNo("");
			cme.setProcessCode(CardContants.CARD_PROC_CANCEL);
			cme.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_CANCEL));
			cme.setCitizenCardNo(cardDataObjList.get(i).getCitizenCardNo());
			cme.setCardPosition(cardPosition);
		//	cme.setCardStatus(CardContants.CARD_STATE_DISABLED);
		//	cme.setApplyWay("");// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
			cardMagList.add(cme);
			cardControlObj.setCurrProcId(currProcId);
			cardControlObj.setLastDate(new Date());
			cardControlObj.setLastOperator(curEmpNo);
			cardControlObj.setCardPosition(cardPosition);
			cardControlObj.setCardControlId(cardDataObjList.get(i).getCardDataId());
			cardControlObj.setClaimStatus(claimStatus);
			cardControlObjList.add(cardControlObj);
		}
		cmm.batchInsert(cardMagList);
		
		
		// 更新控制表
		cardControlMap.updateIncomingCancelBycitizenNo(cardControlObjList);
		
		
		if("01".equals(storageMode)){
			//3.1更新批次任务表
			//更新前锁死
			cbm.updateByIncomingCancel(makeBatchNoList);
			//3.2更新任务表
			ctm.updateByIncomingCancel(taskNoList);
			
			
			List<CardData> cardDataList = new ArrayList<CardData>();
			List<String> citizenCardNoList = new ArrayList<String>();
			List<ApplyBatchInfo> batchInfoList = abim.queryBatchInfoBymakeNoList(makeBatchNoList);
			for(int i=0;i<batchInfoList.size();i++){
				ApplyBatchInfo applyBatchObj = batchInfoList.get(i);
				String cardBatchFileType = applyBatchObj.getBatchFileName();
				if("RJMK".equals(cardBatchFileType)){
					CardData cardDataToUpdate = new CardData();
					cardDataToUpdate.setCardDataId(applyBatchObj.getCardDataId());
					cardDataList.add(cardDataToUpdate);
				}
				
		//		citizenCardNoList.add(applyBatchObj.getCitizenCardNo());
			}
			//3.3更新卡号库表
			// 只能通过读取文件来搜集卡号（成功+失败）
			String sourceSuccessPath = RESPONSESUCCESS_PATH;
			List<String[]> segmentToUpdateList = new ArrayList<String[]>();
			citizenCardNoList = parseFile.readMakeCardFile(cardBatchList, sourceSuccessPath);
			if(citizenCardNoList.size()==1){
				String segmentString = citizenCardNoList.get(0).substring(5);
				segmentToUpdateList.add(new String[]{segmentString,segmentString});
			}
			if(citizenCardNoList.size()>1){
				segmentToUpdateList = listUtil.modifyCitizenNoList(citizenCardNoList);
			}
			
			List<CardNoGenerated> CardNoGeneratedToUpdate = new ArrayList<CardNoGenerated>();
			if(segmentToUpdateList.size()>0){
				for(int j=0;j<segmentToUpdateList.size();j++){
					String startNo = segmentToUpdateList.get(j)[0];
					String endNo = segmentToUpdateList.get(j)[1];
					//通过起始号和结束号查询卡号库
					List<CardNoGenerated>  cardNoGeneratedList = cardNoGerateMapper.querySegementByStartAndEnd(startNo,endNo);
					if(cardNoGeneratedList.size()==1){
						CardNoGenerated cngObj = cardNoGeneratedList.get(0);
						
						Integer usedAmount = cngObj.getUsedSegmentNo();
						Integer toUpdateAmount = Integer.parseInt(endNo) - Integer.parseInt(startNo)+1;
						cngObj.setUsedSegmentNo(usedAmount-toUpdateAmount);
						cngObj.setIsUseUp("0");
						CardNoGeneratedToUpdate.add(cngObj);
					}
					if(cardNoGeneratedList.size()>1){
						for(int jj=0;jj<cardNoGeneratedList.size();jj++){
							//顺序执行，顺序
							CardNoGenerated cngObj = cardNoGeneratedList.get(jj);
							if(jj==0){
								String db_endNo = cardNoGeneratedList.get(jj).getEndSegmentNo();
								Integer updateAmount = Integer.parseInt(db_endNo) - Integer.parseInt(startNo) + 1;
								Integer usedAmount = cngObj.getUsedSegmentNo();
								cngObj.setUsedSegmentNo(usedAmount-updateAmount);
								cngObj.setIsUseUp("0");
								CardNoGeneratedToUpdate.add(cngObj);
							}else if(jj==(cardNoGeneratedList.size()-1)){
								String db_startNo = cardNoGeneratedList.get(jj).getStartSegmentNo();
								Integer updateAmount = Integer.parseInt(endNo) - Integer.parseInt(db_startNo) + 1;
								Integer usedAmount = cngObj.getUsedSegmentNo();
								cngObj.setUsedSegmentNo(usedAmount-updateAmount);
								cngObj.setIsUseUp("0");
								CardNoGeneratedToUpdate.add(cngObj);
							}else{
								cngObj.setUsedSegmentNo(0);
								cngObj.setIsUseUp("0");
								CardNoGeneratedToUpdate.add(cngObj);
							}
						}
					}
				}
			}
			
			
			//更新卡号库段
			if(CardNoGeneratedToUpdate.size()>0){
				cardNoGerateMapper.batchUpdateAmount(CardNoGeneratedToUpdate);
			}
			
			
			//3.4更新卡数据表
			if(cardDataList.size()>0){
				cdm.batchUpdateByIncomingCancel(cardDataList);
			}
			
			
			
			
		}

		//4.删除入库明细表
		if("01".equals(storageMode)||"02".equals(storageMode)||"03".equals(storageMode)||"04".equals(storageMode)){
			stockdm.deleteByIncomingCancel(storageNo);
		}else if("11".equals(storageMode)){
			stockdm.updateByOutgoingCancel(storageNo);
		}else if("13".equals(storageMode)||"15".equals(storageMode)){
			stockdm.deleteByOutingCancel(storageNo);
		}
		
		//4.删除入库记录表
		sdm.deleteByCancel(storageNo);
		
		//5.移动文件
		if("01".equals(storageMode)){
			parseFile.moveMakeCardFile(cardBatchList, sourceBasePath,targeBasetPath);
		}else if("03".equals(storageMode)||"04".equals(storageMode)){
			parseFile.moveFile(distributeTaskNoList, sourceBasePath,targeBasetPath);
		}else if("13".equals(storageMode)||"15".equals(storageMode)){
			parseFile.deleteFile(distributeTaskNoList, sourceBasePath);
		}	
	}
	
	//cardTurnInRegister
	@Override
	@SystemServiceLog(description = "空白卡/成品卡上缴登记")
	@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
	public Map<String, Object> cardTurnInRegister(HttpServletRequest request) throws InventoryException {
		
		String[] cardPCodeArray = request.getParameterValues("cardCodeByCardTurnIn");
		String[] cardTypeArray = request.getParameterValues("cardTypeByCardTurnIn");
		String[] citizenCardNoArray = request.getParameterValues("cardNoByCardTurnIn");
		String[] stockTypeArray = request.getParameterValues("stockTypeByCardTurnIn");
		
		String branchNo = request.getParameter("branchNoByCardTurnIn");
		String opeNo = request.getParameter("empNoByCardTurnIn");
		
		//返回的打印用参数map
		//卡产品代码列表
		List<String> cardPCodeList = new ArrayList<String>();
		//市民卡号代码，数量列表
		List<String> citizenCardNoList = new ArrayList<String>();
		//卡产品代码对应数量（卡产品代码，数量）
		Map<String,Integer> cardPCodeAndAmount = new HashMap<String,Integer>();
		//卡产品名称列表
		List<String> cardPNameList = new ArrayList<String>();
		//卡控制ID列表
		List<String> cardControlIdList = new ArrayList<String>();
		//卡产品数量列表
		List<Integer> amountList = new ArrayList<Integer>();
		//配送文件参数
		List<String> paramList = new ArrayList<String>();
		//市民卡与库存卡片种类的map
		Map<String,String> cardNoAndStocTypeMap = new HashMap<String,String>();
		//卡产品代码对应的卡产品名称map
		Map<String,String> cardCodeAndCardNameMap = new HashMap<String,String>();
				
		//卡物理类型代码，对应的名称
		Map<String,String> cardTypeCodeAndNameMap = new HashMap<String,String>();
		
		for(int j=0;j<citizenCardNoArray.length;j++){
			cardNoAndStocTypeMap.put(citizenCardNoArray[j], stockTypeArray[j]);
		}
		
		//通过市民卡号列表查询出cardData集合
		citizenCardNoList = Arrays.asList(citizenCardNoArray);
		List<CardData> cardDataList = cdm.queryCardDataByCitizenCardNoList(citizenCardNoList);
		for(int i=0;i<cardDataList.size();i++){
			CardData cardDataObj = cardDataList.get(i);
			String cardPCode = cardDataObj.getCardpCode();
			String citizenCardNo = cardDataObj.getCitizenCardNo();
			String physicType = cardDataObj.getCardPhysicalType();
			String stockType = cardNoAndStocTypeMap.get(citizenCardNo);
			String cardPCodeAndType = cardPCode+"#"+physicType+"#"+stockType;
			String param = citizenCardNo+"#"+cardPCodeAndType;
			//卡控制列表
			cardControlIdList.add(String.valueOf(cardDataObj.getCardDataId()));
			paramList.add(param);
			cardPCodeList.add(cardPCode);
			if(cardPCodeAndAmount.containsKey(cardPCodeAndType)){
				Integer amount = cardPCodeAndAmount.get(cardPCodeAndType);
				cardPCodeAndAmount.put(cardPCodeAndType, amount+1);
			}else{
				cardPCodeAndAmount.put(cardPCodeAndType, 1);
			}
			
		}
		logger.debug("cardPCodeAndAmount==>"+cardPCodeAndAmount);
		HashSet<String> h = new HashSet<String>(cardPCodeList);   
		cardPCodeList.clear();   
		cardPCodeList.addAll(h);   
		List<CardProdunctDefinition> cardProDefObj = cpdm.queryCardNameByCode(cardPCodeList);
		for(int m=0;m<cardProDefObj.size();m++){
			CardProdunctDefinition cardDef = cardProDefObj.get(m);
			cardCodeAndCardNameMap.put(cardDef.getCardpCode(), cardDef.getCardpName());
		}
		//查询卡片物理类型名称
		List<CardPhysicsType> cardPhysicTypeList = cptm.queryAllCardPhysicsType();
		for(int n=0;n<cardPhysicTypeList.size();n++){
			CardPhysicsType cardTypeObj = cardPhysicTypeList.get(n);
			cardTypeCodeAndNameMap.put(cardTypeObj.getCardTypeCode(), cardTypeObj.getCardTypeName());
		}
		
		Integer totalAmount = cardControlIdList.size();		
		
		String distributeTaskNo = inventoryRecordNoUtil.getDistributeTaskNo();
		logger.debug("distributeTaskNo===>"+distributeTaskNo);
		
		//出入库记录
		String storageNo = inventoryRecordNoUtil.getStorageNo();
		logger.debug("新的出入库号==>"+storageNo);
		StorageReg sr=new StorageReg();
		sr.setStorageNo(storageNo);
		sr.setBussinessNo("");
		sr.setStorageDetailNo("");
		sr.setAmount(totalAmount);
		sr.setStorageMode("13");
		//入库为1
		sr.setStorageType("1");
		sr.setStorageReason("白卡/成品卡上缴");
		sr.setStorageDate(DateAndStampUtil.getCurrentDate());
		sr.setRevocationDate("");
		sr.setRevocationOperatorNo("");
		sr.setRevocationBranchNo("");
		sr.setStartNo("");
		sr.setEndNo("");
		sr.setStorageStatus("1");
		sr.setSourcePosition("2");
		sr.setDesPosition("1");
		sr.setSourceBranchNo(branchNo);
		//中心库网点，这里写死
		sr.setDesBranchNo("10000000");
		sr.setIsReceive("");
		sr.setBothSeqNo("");
		sr.setDataInMode("0");
		sr.setOperatorNo(opeNo);
		sr.setOperateBranchNo(branchNo);
		sr.setInputDate(DateAndStampUtil.getCurrentDate());
		sr.setRemark("");
		sr.setRevocationBussinessNo("");
		logger.debug("sr==>"+sr.toString());
		//插入出入库登记表
		srm.insert(sr);
		
		
		//入库明细
		String detailNo = getDetailNo();
		StorageDetail sd=new StorageDetail();
		
		sd.setStorageDetailNo(detailNo);
		sd.setStorageNo(storageNo);
		sd.setDistributeTaskNo(distributeTaskNo);
		sd.setAmount(totalAmount);
		logger.debug("sd==>"+sd);
		sdm.insert(sd);//更新出入库明细表
		
		//库存汇总
		String ID = stockdm.queryMaxDetailId();
		if("".equals(ID)||null==ID){
				ID = "1";
		}
		int id = Integer.parseInt(ID)+1;
		Set<Map.Entry<String,Integer>> entrySet = cardPCodeAndAmount.entrySet();
		for(Map.Entry<String,Integer> entry:entrySet){
			StockSum ss = new StockSum();
			String cardPCodeAndType = entry.getKey();
			String[] cardArray = cardPCodeAndType.split("#");
			String cardCode = cardArray[0];
			String cardPhysicType = cardArray[1];
			String cardStockType = cardArray[2];
			String cardPName = cardCodeAndCardNameMap.get(cardCode)+cardTypeCodeAndNameMap.get(cardPhysicType);
			cardPNameList.add(cardPName);
			amountList.add(entry.getValue());
			ss.setBranchNo(branchNo);
			ss.setCardpCode(cardCode);
			ss.setStockPosition("2");
			ss.setCardPhysicType(cardPhysicType);
			ss.setCardStockType(cardStockType);
			//现根据卡产品代码，网点编号，stockStatus=1条件查询库中是否有数据，			
			String stockSumID = ssm.queryStockSumNoByCardPCode(ss);
			logger.debug("库存汇总ID==>"+stockSumID);
			
			//更新前，锁死要更新的行
			StockSum stockSumObjTemp = ssm.queryStockSumBySumId(stockSumID);
			ss.setLastOperator(opeNo);
			ss.setLastModDate(DateAndStampUtil.getCurrentDate());
			ss.setOperatorAmount(entry.getValue());
			ss.setStockSumId(stockSumID);
			
			logger.debug("ss==>"+ss.toString());
			ssm.updateStockSumByDistributeToCenter(ss);

			
			
			StockDetail stockDetail = new StockDetail();
			stockDetail.setStockSumId(stockSumID);
			stockDetail.setStockDetailId(id);
			stockDetail.setTaskNo("");
		//制卡返回文件号，这里不需要，可以从入库出库明细中查询
		//	stockDetail.setMakecardReturnNo(makeCardNoList.get(i));
			stockDetail.setItemAttrVal03("");
			stockDetail.setItemAttrVal04("");
			stockDetail.setItemAttrVal05("");
			stockDetail.setAmount(entry.getValue());
			stockDetail.setInStockStat("1");
			stockDetail.setLstInNo("");
			stockDetail.setLstOutNo(storageNo);
			stockDetail.setLstInDate("");
			stockDetail.setLstOutDate(DateAndStampUtil.getCurrentDate());
			stockDetail.setLstInOperator("");
			stockDetail.setLstOutOperator(opeNo);
			stockDetail.setFileDate("");
			stockDetail.setFileFlag("");
			logger.debug("stockDetail===>"+stockDetail.toString());
			stockdm.insert(stockDetail);
			id++;
		}
		
		//插入卡管理表
		List<CardData> cardDataObjList = cdm.queryCardDataByCardControlIdList(cardControlIdList);
		//卡过程表
		Date currentDate = new Date();
		List<CardManage> cardMagList = new ArrayList<CardManage>();
		List<CardControl> cardControlObjList = new ArrayList<CardControl>();
		for(int i=0;i<cardDataObjList.size();i++){
			CardManage cme = new CardManage();
			CardControl cardControlObj = new CardControl();
			String currProcId = UUID.randomUUID().toString().replace("-", "");
			cme.setProcessId(currProcId);
			cme.setApplyBranchNo(branchNo);
			cme.setApplyDate(new Date());
			cme.setApplyTellerNo(opeNo);
			cme.setBusinessNo("");
			cme.setProcessCode(CardContants.CARD_PROC_HANDED);
			cme.setProcessName("网点上缴配送出库");
			cme.setCitizenCardNo(cardDataObjList.get(i).getCitizenCardNo());
			cme.setCardPosition(CardContants.CARD_POSITION_OTHER);
		//	cme.setCardStatus(CardContants.CARD_STATE_DISABLED);
		//	cme.setApplyWay("");// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
			cardMagList.add(cme);
			cardControlObj.setCurrProcId(currProcId);
			cardControlObj.setLastDate(currentDate);
			cardControlObj.setLastOperator(opeNo);
			cardControlObj.setCardPosition("9");
			cardControlObj.setCardControlId(cardDataObjList.get(i).getCardDataId());
			cardControlObjList.add(cardControlObj);
		}
		cmm.batchInsert(cardMagList);
		
		
		//更新卡控制状态
		//更新控制ID,先进行行加锁
		List<String> cardPositionList = cardControlMap.queryCardPositionByControlId(cardControlIdList);
		cardControlMap.updateCardControlByDistributeToCenter(cardControlObjList);
		
		
		//组装打印参数
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("storageNo", storageNo);
		//网点号
		resultMap.put("branchNo", branchNo);
		//出入库总数量(因为这里是只选择一项，数量暂时这么编辑，后期需要改正)
		resultMap.put("totalAmount", String.valueOf(totalAmount));
		//出入库日期
		resultMap.put("curDate", DateAndStampUtil.getCurrentDate());
		//清单明细抬头
		resultMap.put("title", "空白卡/成品卡上缴清单");
		//卡产品名称列表
		
		resultMap.put("cardPNameList", cardPNameList);
		//制卡批号列表
		resultMap.put("makeCardNoList", "");
		//制卡商名称列表
		resultMap.put("companyList", "");
		//每个批号的数量列表
		resultMap.put("amountList", amountList);
		//凭证类型
		resultMap.put("credential_type", "storage");
		logger.debug("resultMap==>"+resultMap);
		
		//预览PDF
		createStoragePDF(resultMap);
		
		
		//生成白卡配送任务清单
		createDistributeTaskFile(paramList,distributeTaskNo);
		
		Map<String,Object> rMap = new HashMap<String,Object>();
		rMap.put("credential_type", "storage");
		rMap.put("ipAddress", IP_ADDRESS);
		rMap.put("storageNo", storageNo);
		rMap.put("title", "空白卡/成品卡上缴清单");
		return rMap;
	}
	
	@Override
	public Map<String, Object> rejectCardTurnInRegister(HttpServletRequest request) throws InventoryException {
		
		String[] cardPCodeArray = request.getParameterValues("cardCodeByTurnInRejectCard");
		String[] cardTypeArray = request.getParameterValues("cardTypeByTurnInRejectCard");
		String[] citizenCardNoArray = request.getParameterValues("cardNoByTurnInRejectCard");
		String[] stockTypeArray = request.getParameterValues("stockTypeByTurnInRejectCard");
		
		String branchNo = request.getParameter("branchNoByTurnInRejectCard");
		String opeNo = request.getParameter("empNoByTurnInRejectCard");
		
		//返回的打印用参数map
		//卡产品代码列表
		List<String> cardPCodeList = new ArrayList<String>();
		//市民卡号代码，数量列表
		List<String> citizenCardNoList = new ArrayList<String>();
		//卡产品代码对应数量（卡产品代码，数量）
		Map<String,Integer> cardPCodeAndAmount = new HashMap<String,Integer>();
		//卡产品名称列表
		List<String> cardPNameList = new ArrayList<String>();
		//卡控制ID列表
		List<String> cardControlIdList = new ArrayList<String>();
		//卡产品数量列表
		List<Integer> amountList = new ArrayList<Integer>();
		//配送文件参数
		List<String> paramList = new ArrayList<String>();
		//市民卡与库存卡片种类的map
		Map<String,String> cardNoAndStocTypeMap = new HashMap<String,String>();
		//卡产品代码对应的卡产品名称map
		Map<String,String> cardCodeAndCardNameMap = new HashMap<String,String>();
				
		//卡物理类型代码，对应的名称
		Map<String,String> cardTypeCodeAndNameMap = new HashMap<String,String>();
		
		for(int j=0;j<citizenCardNoArray.length;j++){
			cardNoAndStocTypeMap.put(citizenCardNoArray[j], stockTypeArray[j]);
		}
		
		//通过市民卡号列表查询出cardData集合
		citizenCardNoList = Arrays.asList(citizenCardNoArray);
		List<CardData> cardDataList = cdm.queryCardDataByCitizenCardNoList(citizenCardNoList);
		for(int i=0;i<cardDataList.size();i++){
			CardData cardDataObj = cardDataList.get(i);
			String cardPCode = cardDataObj.getCardpCode();
			String citizenCardNo = cardDataObj.getCitizenCardNo();
			String physicType = cardDataObj.getCardPhysicalType();
			String stockType = cardNoAndStocTypeMap.get(citizenCardNo);
			String cardPCodeAndType = cardPCode+"#"+physicType+"#"+stockType;
			String param = citizenCardNo+"#"+cardPCodeAndType;
			//卡控制列表
			cardControlIdList.add(String.valueOf(cardDataObj.getCardDataId()));
			paramList.add(param);
			cardPCodeList.add(cardPCode);
			if(cardPCodeAndAmount.containsKey(cardPCodeAndType)){
				Integer amount = cardPCodeAndAmount.get(cardPCodeAndType);
				cardPCodeAndAmount.put(cardPCodeAndType, amount+1);
			}else{
				cardPCodeAndAmount.put(cardPCodeAndType, 1);
			}
			
		}
		logger.debug("cardPCodeAndAmount==>"+cardPCodeAndAmount);
		HashSet<String> h = new HashSet<String>(cardPCodeList);   
		cardPCodeList.clear();   
		cardPCodeList.addAll(h);   
		List<CardProdunctDefinition> cardProDefObj = cpdm.queryCardNameByCode(cardPCodeList);
		for(int m=0;m<cardProDefObj.size();m++){
			CardProdunctDefinition cardDef = cardProDefObj.get(m);
			cardCodeAndCardNameMap.put(cardDef.getCardpCode(), cardDef.getCardpName());
		}
		//查询卡片物理类型名称
		List<CardPhysicsType> cardPhysicTypeList = cptm.queryAllCardPhysicsType();
		for(int n=0;n<cardPhysicTypeList.size();n++){
			CardPhysicsType cardTypeObj = cardPhysicTypeList.get(n);
			cardTypeCodeAndNameMap.put(cardTypeObj.getCardTypeCode(), cardTypeObj.getCardTypeName());
		}
		
		Integer totalAmount = cardControlIdList.size();		
		
		String distributeTaskNo = inventoryRecordNoUtil.getDistributeTaskNo();
		logger.debug("distributeTaskNo===>"+distributeTaskNo);
		
		//出入库记录
		String storageNo = inventoryRecordNoUtil.getStorageNo();
		logger.debug("新的出入库号==>"+storageNo);
		StorageReg sr=new StorageReg();
		sr.setStorageNo(storageNo);
		sr.setBussinessNo("");
		sr.setStorageDetailNo("");
		sr.setAmount(totalAmount);
		sr.setStorageMode("15");
		//入库为1
		sr.setStorageType("1");
		sr.setStorageReason("废卡/注销卡上缴");
		sr.setStorageDate(DateAndStampUtil.getCurrentDate());
		sr.setRevocationDate("");
		sr.setRevocationOperatorNo("");
		sr.setRevocationBranchNo("");
		sr.setStartNo("");
		sr.setEndNo("");
		sr.setStorageStatus("1");
		sr.setSourcePosition("2");
		sr.setDesPosition("1");
		sr.setSourceBranchNo(branchNo);
		//中心库网点，这里写死
		sr.setDesBranchNo("10000000");
		sr.setIsReceive("");
		sr.setBothSeqNo("");
		sr.setDataInMode("0");
		sr.setOperatorNo(opeNo);
		sr.setOperateBranchNo(branchNo);
		sr.setInputDate(DateAndStampUtil.getCurrentDate());
		sr.setRemark("");
		sr.setRevocationBussinessNo("");
		logger.debug("sr==>"+sr.toString());
		//插入出入库登记表
		srm.insert(sr);
		
		
		//入库明细
		String detailNo = getDetailNo();
		StorageDetail sd=new StorageDetail();
		
		sd.setStorageDetailNo(detailNo);
		sd.setStorageNo(storageNo);
		sd.setDistributeTaskNo(distributeTaskNo);
		sd.setAmount(totalAmount);
		logger.debug("sd==>"+sd);
		sdm.insert(sd);//更新出入库明细表
		
		//库存汇总
		String ID = stockdm.queryMaxDetailId();
		if("".equals(ID)||null==ID){
				ID = "1";
		}
		int id = Integer.parseInt(ID)+1;
		Set<Map.Entry<String,Integer>> entrySet = cardPCodeAndAmount.entrySet();
		for(Map.Entry<String,Integer> entry:entrySet){
			StockSum ss = new StockSum();
			String cardPCodeAndType = entry.getKey();
			String[] cardArray = cardPCodeAndType.split("#");
			String cardCode = cardArray[0];
			String cardPhysicType = cardArray[1];
			String cardStockType = cardArray[2];
			String cardPName = cardCodeAndCardNameMap.get(cardCode)+cardTypeCodeAndNameMap.get(cardPhysicType);
			cardPNameList.add(cardPName);
			amountList.add(entry.getValue());
			ss.setBranchNo(branchNo);
			ss.setCardpCode(cardCode);
			ss.setStockPosition("2");
			ss.setCardPhysicType(cardPhysicType);
			ss.setCardStockType(cardStockType);
			ss.setCardpName(cardCodeAndCardNameMap.get(cardCode));
			//现根据卡产品代码，网点编号，stockStatus=1条件查询库中是否有数据，			
			String stockSumID = ssm.queryStockSumNoByCardPCode(ss);
			
			logger.debug("库存汇总ID==>"+stockSumID);
			String stockSumIDToUpdate = null;
			if("".equals(stockSumID) || stockSumID==null){
				//查找库存汇总表中最大的ID号
				String newID = null;
				String maxStockSumID = ssm.queryMaxStockSumID();
				Integer no = Integer.parseInt(maxStockSumID.substring(4))+1;
				//取得的数字的长度
				int numLength = String.valueOf(no).length();
				//判断取得的数字长度与字段长度，如果小于字段长度，那么说明字段的数字位是以0开头的，需要补位
				int addZero = maxStockSumID.substring(4).length()-numLength;
				if(addZero>0){
					int len = maxStockSumID.substring(4).length();
					newID = "KCHZ"+String.format("%0" + len + "d", no);
				}
				if(addZero==0){
					newID = "KCHZ"+no;
				}
				logger.debug("库存出入库汇总号是==>"+newID);
				ss.setStockSumId(newID);
				ss.setTotalNum(0);
				ss.setCurrNum(0);
				ss.setRealOutNum(0);
				ss.setOutSum(0);
				ssm.insertNewStockInfo(ss);
				stockSumIDToUpdate = newID;
			}else{

				stockSumIDToUpdate = stockSumID;
			}
			
			//更新前，锁死要更新的行
			StockSum stockSumObjTemp = ssm.queryStockSumBySumId(stockSumIDToUpdate);
			
			ss.setLastOperator(opeNo);
			ss.setLastModDate(DateAndStampUtil.getCurrentDate());
			ss.setOperatorAmount(entry.getValue());
			
			logger.debug("ss==>"+ss.toString());
			ssm.updateStockSumByDistributeToCenter(ss);

			
			
			StockDetail stockDetail = new StockDetail();
			stockDetail.setStockSumId(stockSumIDToUpdate);
			stockDetail.setStockDetailId(id);
			stockDetail.setTaskNo("");
		//制卡返回文件号，这里不需要，可以从入库出库明细中查询
		//	stockDetail.setMakecardReturnNo(makeCardNoList.get(i));
			stockDetail.setItemAttrVal03("");
			stockDetail.setItemAttrVal04("");
			stockDetail.setItemAttrVal05("");
			stockDetail.setAmount(entry.getValue());
			stockDetail.setInStockStat("1");
			stockDetail.setLstInNo("");
			stockDetail.setLstOutNo(storageNo);
			stockDetail.setLstInDate("");
			stockDetail.setLstOutDate(DateAndStampUtil.getCurrentDate());
			stockDetail.setLstInOperator("");
			stockDetail.setLstOutOperator(opeNo);
			stockDetail.setFileDate("");
			stockDetail.setFileFlag("");
			logger.debug("stockDetail===>"+stockDetail.toString());
			stockdm.insert(stockDetail);
			id++;
		}
		
		//插入卡管理表
		List<CardData> cardDataObjList = cdm.queryCardDataByCardControlIdList(cardControlIdList);
		//卡过程表
		//查询出卡号
		List<CardManage> cardMagList = new ArrayList<CardManage>();
		List<CardControl> cardControlObjList = new ArrayList<CardControl>();
		for(int i=0;i<cardDataObjList.size();i++){
			CardManage cme = new CardManage();
			CardControl cardControl = new CardControl();
			String currProcId = UUID.randomUUID().toString().replace("-", "");
			cme.setProcessId(currProcId);
			cme.setApplyBranchNo(branchNo);
			cme.setApplyDate(new Date());
			cme.setApplyTellerNo(opeNo);
			cme.setBusinessNo("");
			cme.setProcessCode(CardContants.CARD_PROC_HANDED);
			cme.setProcessName("网点上缴配送出库");
			cme.setCitizenCardNo(cardDataObjList.get(i).getCitizenCardNo());
			cme.setCardPosition(CardContants.CARD_POSITION_OTHER);
		//	cme.setCardStatus(CardContants.CARD_STATE_DISABLED);
		//	cme.setApplyWay("");// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
			cardMagList.add(cme);
			
			cardControl.setCurrProcId(currProcId);
			cardControl.setLastDate(new Date());
			cardControl.setLastOperator(opeNo);
			cardControl.setCardPosition("9");
			cardControl.setCardControlId(cardDataObjList.get(i).getCardDataId());
			cardControlObjList.add(cardControl);
		}
		cmm.batchInsert(cardMagList);
		
		//更新卡控制状态
		//更新控制ID,先进行行加锁
		List<String> cardPositionList = cardControlMap.queryCardPositionByControlId(cardControlIdList);
		cardControlMap.updateControlByDistribution(cardControlObjList);
		
		//组装打印参数
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("storageNo", storageNo);
		//网点号
		resultMap.put("branchNo", branchNo);
		//出入库总数量(因为这里是只选择一项，数量暂时这么编辑，后期需要改正)
		resultMap.put("totalAmount", String.valueOf(totalAmount));
		//出入库日期
		resultMap.put("curDate", DateAndStampUtil.getCurrentDate());
		//清单明细抬头
		resultMap.put("title", "废卡上缴清单");
		//卡产品名称列表
		
		resultMap.put("cardPNameList", cardPNameList);
		//制卡批号列表
		resultMap.put("makeCardNoList", "");
		//制卡商名称列表
		resultMap.put("companyList", "");
		//每个批号的数量列表
		resultMap.put("amountList", amountList);
		//凭证类型
		resultMap.put("credential_type", "storage");
		logger.debug("resultMap==>"+resultMap);
		
		//预览清单
		createStoragePDF(resultMap);
		
		//生成白卡配送任务清单
		createDistributeTaskFile(paramList,distributeTaskNo);
		
		Map<String,Object> rMap = new HashMap<String,Object>();
		
		rMap.put("credential_type", "storage");
		rMap.put("ipAddress", IP_ADDRESS);
		rMap.put("storageNo", "storageNo");
		rMap.put("title", "废卡上缴清单");
		
		return rMap;
	}
	
	/**
	 * 编号：6-1-1
	 * 功能：上缴卡片至中心库
	 */
	@SystemServiceLog(description = "上缴卡片至中心库")
	public Map<String,Object> cardhanding(String[] paramArray) {
		//返回打印需要的参数map
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//卡产品代码列表
		List<String> cardPCodeList = new ArrayList<String>();
		//卡产品列表
		List<CardProdunctDefinition> cardPObjList = new ArrayList<CardProdunctDefinition>();
		//卡产品名称列表
		List<String> cardPNameList = new ArrayList<String>();
		//卡产品名称对应卡产品代码的map
		Map<String,String> cardCodeAndName = new HashMap<String,String>();
		//每个卡产品对应的数量
		List<String> amountByCardP = new ArrayList<String>();
		
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		
		HashMap<String, Object> cdmap = new HashMap<String, Object>();
		List<CardData> cdlist = new ArrayList<CardData>();
		List<String> str = new ArrayList<String>();
		
		for(int i = 0;i < paramArray.length;i++){
		   String param = paramArray[i];
		   String[] item = param.split("#");
		   String citizenNo = item[0];
		   String cardpCode = item[1];
		   CardData cd=cdm.queryCardDataByCitizenCardNo(citizenNo);
		   cdlist.add(cd);
		   str.add(cardpCode);
		}
		
		logger.debug("cdlist==>"+cdlist);
		HashMap<String, Integer> hs = new HashMap<String, Integer>();
		for (String string : str) {
			Integer count = 1;
			if(hs.get(string) != null) {
				count = hs.get(string) + 1;
			}
			hs.put(string, count);
		}
		  Set keySet = hs.keySet(); // key的set集合  
	        Iterator it = keySet.iterator();  
	        while(it.hasNext()){  
	        	List<String> smk = new ArrayList<String>();
	            String k = (String) it.next(); // key  
	            //将卡产品代码加入list
	            cardPCodeList.add(k);
	            
	            for(int i = 0;i < cdlist.size();i++){
					if(cdlist.get(i).getCardpCode().equals(k)){
						logger.debug("getCitizenCardNo==>"+cdlist.get(i).getCitizenCardNo());
						smk.add(cdlist.get(i).getCitizenCardNo());
						logger.debug("smk==>"+smk);
					}
				} 
	            cdmap.put(k, smk);
	        } 
	        
	        logger.debug("hs==>"+hs);
			logger.debug("cdmap==>"+cdmap);
			
			
			//获得卡产品名称
			cardPObjList = cpdm.queryCardNameByCode(cardPCodeList);
			for(int i=0;i<cardPObjList.size();i++){
				String cardPName = cardPObjList.get(i).getCardpName();
				String cardPCode = cardPObjList.get(i).getCardpCode();
				cardPNameList.add(cardPName);
				cardCodeAndName.put(cardPName, cardPCode);
			}
			logger.debug("cardCodeAndName====>"+cardCodeAndName);
			
			//1.生成出入库记录
			//  1.1生成出入库单号
			String storageNo = inventoryRecordNoUtil.getStorageNo();
			logger.debug("storageNo==>"+storageNo);
			StorageReg sr=new StorageReg();
			sr.setStorageNo(storageNo);
			sr.setBussinessNo("");
			sr.setStorageDetailNo("");
			sr.setAmount(paramArray.length);
			sr.setStorageMode("13");
			sr.setStorageType("1");
			sr.setStorageReason("空白卡/成品卡配送出库");
			sr.setStorageDate(DateAndStampUtil.getCurrentDate());
			sr.setRevocationDate("");
			sr.setRevocationOperatorNo("");
			sr.setRevocationBranchNo("");
			sr.setStartNo("");
			sr.setEndNo("");
			sr.setStorageStatus("1");
			sr.setSourcePosition("2");
			sr.setDesPosition("0");
			sr.setSourceBranchNo(activeUser.getBranchNo());
			//手动设置网点编号10000000
			sr.setDesBranchNo("10000000");
			sr.setIsReceive("0");
			sr.setBothSeqNo("");
			sr.setDataInMode("0");
			sr.setOperatorNo(activeUser.getUserNo().toString());
			sr.setOperateBranchNo(activeUser.getBranchNo());
			sr.setInputDate(DateAndStampUtil.getCurrentDate());
			sr.setRemark("");
			sr.setRevocationBussinessNo("");
			logger.debug("sr==>"+sr);
			srm.insert(sr);//插入出入库登记表
			
			//2.生成出入库明细记录
			String distributeTaskNo = inventoryRecordNoUtil.getDistributeTaskNo();
			logger.debug("distributeTaskNo===>"+distributeTaskNo);
			StorageDetail storageDetail = new StorageDetail();
			String storageDetailNo = getDetailNo();
			storageDetail.setStorageNo(storageNo);
			storageDetail.setStorageDetailNo(storageDetailNo);
			storageDetail.setAmount(paramArray.length);
			storageDetail.setDistributeTaskNo(distributeTaskNo);
			sdm.insert(storageDetail);
			
			//更新库存汇总表
			//取出卡产品代码，编辑map（卡产品代码，数量）
			 Set key = hs.keySet(); // key的set集合  
		        Iterator its = keySet.iterator();  
		        while(its.hasNext()){  
		        	List<String> smk = new ArrayList<String>();
		        	String k = (String) its.next(); // key 
		            Integer v = hs.get(k);  //value
		            //更新网点的库存汇总表
		            StockSum ssObj = new StockSum();
		            ssObj.setCardpCode(k);
		            ssObj.setStockPosition("2");
		            ssObj.setBranchNo(activeUser.getBranchNo());
		            ssObj.setOperatorAmount(v);
		            ssObj.setLastOperator(activeUser.getUserNo().toString());
		            ssObj.setLastModDate(DateAndStampUtil.getCurrentDate());
					//ssm.updateStockSumByCardHand(ssObj);
					
			
					
					//现根据卡产品代码，网点编号，stockStatus=1条件查询库中是否有数据，
					//如果没有则插入一条数据，然后再更新
					//如果有，则直接更新
					
					String stockSumID = ssm.queryStockSumNoByCardPCode(ssObj);
					logger.debug("库存汇总ID==>"+stockSumID);
					if("".equals(stockSumID) || stockSumID==null){
						//查找库存汇总表中最大的ID号
						String newID = null;
						String maxStockSumID = ssm.queryMaxStockSumID();
						Integer no = Integer.parseInt(maxStockSumID.substring(4))+1;
						//取得的数字的长度
						int numLength = String.valueOf(no).length();
						//判断取得的数字长度与字段长度，如果小于字段长度，那么说明字段的数字位是以0开头的，需要补位
						int addZero = maxStockSumID.substring(4).length()-numLength;
						if(addZero>0){
							int len = maxStockSumID.substring(4).length();
							newID = "KCHZ"+String.format("%0" + len + "d", no);
						}
						if(addZero==0){
							newID = "KCHZ"+no;
						}
						logger.debug("库存出入库汇总号是==>"+newID);
						ssObj.setStockSumId(newID);
						ssObj.setTotalNum(0);
						ssObj.setCurrNum(0);
						ssObj.setRealOutNum(0);
						ssObj.setOutSum(0);
						ssm.insertNewStockInfo(ssObj);
					}
							
					ssObj.setLastOperator(activeUser.getUserNo().toString());
					ssObj.setLastModDate(DateAndStampUtil.getCurrentDate());
					ssObj.setOperatorAmount(v);
					logger.debug("对应的卡产品数量==>"+v);
					ssm.updateStockSumByDistributeToCenter(ssObj);
					
				//   库存汇总ID，需要查询出来
					String stockSumid = ssm.queryStockSumNoByCardPCode(ssObj);
					
					String ID = stockdm.queryMaxDetailId();
					if("".equals(ID)||null==ID){
							ID = "1";
					}
					int id = Integer.parseInt(ID)+1;
					StockDetail stockDetail = new StockDetail();
					stockDetail.setStockSumId(stockSumid);
					stockDetail.setStockDetailId(id);
					stockDetail.setTaskNo("");
					stockDetail.setMakecardReturnNo("");
					stockDetail.setItemAttrVal03("");
					stockDetail.setItemAttrVal04("");
					stockDetail.setItemAttrVal05("");
					stockDetail.setAmount(v);
					stockDetail.setInStockStat("1");
					stockDetail.setLstInNo("");
					stockDetail.setLstOutNo(storageNo);
					stockDetail.setLstInDate("");
					stockDetail.setLstOutDate(DateAndStampUtil.getCurrentDate());
					stockDetail.setLstInOperator("");
					stockDetail.setLstOutOperator(activeUser.getUserNo().toString());
					stockDetail.setFileDate("");
					stockDetail.setFileFlag("");
					logger.debug("stockDetail===>"+stockDetail.toString());
					stockdm.insert(stockDetail);		
			}
		        
		        //更新卡控制表
				List<String> cclist = new ArrayList<String>();
				for(int i = 0;i < paramArray.length;i++){
					   String[] item = paramArray[i].split("#");
					   logger.debug("item====>"+item);
					   CardControl cc=cardControlMap.queryCardControlByCitizenCardNo(item[0]);
					   cc.setCardStatus("99");
					   cclist.add(cc.getCardControlId().toString());
					}
				//不要更新位置
			//	String position="1";
				String claimStatus="97";
				String empNo=activeUser.getUserNo().toString();
				Date lastDate=new Date();
				Date cardDate=null;
				//更新卡状态
	//		    cardControlMap.updateCardControlByDistributeToCenter(cclist, empNo, claimStatus, lastDate, cardDate);
			    
			    
			    //生成上缴卡片任务txt
			    //  文档只记录市民卡号，卡产品代码
	//		    createBlankCardDistributeTaskTxt(paramArray,distributeTaskNo);
			    
			    //出库清单参数
			    //入库号
				resultMap.put("storageNo", storageNo);
				//目的网点号
				resultMap.put("branchNo", "10000000");
				//出库总数量()
				resultMap.put("totalAmount", String.valueOf(paramArray.length));
				//出库日期
				resultMap.put("curDate", DateAndStampUtil.getCurrentDate());
				//清单明细抬头
				resultMap.put("title", "网点上缴卡片出库清单");
				//卡产品名称列表
				resultMap.put("cardPNameList", cardPNameList);
				//配送任务号，抬头标识
				
				resultMap.put("titleByDis", distributeTaskNo);
				//来源网点编号
				resultMap.put("companyList", "");
				//每种卡产品对应的数量
				for(int j=0;j<cardPNameList.size();j++){
					String cardPName = cardPNameList.get(j);
					List<String> cardNoList = (List<String>) cdmap.get(cardCodeAndName.get(cardPName));
					amountByCardP.add(String.valueOf(cardNoList.size()));
				}
				
				resultMap.put("amountList", amountByCardP);
				//凭证类型
				resultMap.put("credential_type", "storage");
			    
				
			    return resultMap;
	}
	
	/**
	 * 生成网点出库任务的电子档：记录包含市民卡号，卡类型代码
	 * @param paramArray
	 */
	/*@SystemServiceLog(description = "生成网点出库任务的电子档")
	private void createBlankCardDistributeTaskTxt(String[] paramArray,String distributeTaskNo) {
		String blankAndRejectTaskFilePath = BLANK_REJECT_TASK_PATH;
		String fileName = distributeTaskNo;
		String targetFilePath = blankAndRejectTaskFilePath+File.separator+distributeTaskNo+".txt";
		logger.debug("targetFilePath===>"+targetFilePath);
		File recordFile = new File(targetFilePath);
		BufferedWriter bw = null;
		OutputStreamWriter osw = null;
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(recordFile);
			osw = new OutputStreamWriter(fos,"utf-8");
			bw = new BufferedWriter(osw);
			//配送任务的标题是：序号|市民卡号|卡产品代码|物理类型|库存分类
			String content = "NO.|CITIZENNO|CARDPCODE";
			bw.write(content);
			for(int i=0;i<paramArray.length;i++){
				String[] subitemArray = paramArray[i].split("#");
				String line = (i+1)+"|"+subitemArray[0]+"|"+subitemArray[1];
				logger.debug("line===>"+line);
				bw.write("\r\n");
				bw.write(line);
			}
			bw.flush();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			if(bw!=null){
				try {
					bw.close();
				} catch (Exception e) {
					
					e.printStackTrace();
				}
			}
			if(osw!=null){
				try {
					osw.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if(fos!=null){
				try {
					fos.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}*/
	
	/**
	 * 生成网点出库任务的电子档：记录包含市民卡号，卡类型代码
	 * @param paramArray
	 * @throws InventoryException 
	 */
	@SystemServiceLog(description = "生成网点出库任务的电子档")
	private void createDistributeTaskFile(List<String> paramList,String distributeTaskNo) throws InventoryException {
		String blankAndRejectTaskFilePath = BLANK_REJECT_TASK_PATH;
		String fileName = distributeTaskNo;
		String targetFilePath = blankAndRejectTaskFilePath+File.separator+distributeTaskNo+".txt";
		logger.debug("targetFilePath===>"+targetFilePath);
		File recordFile = new File(targetFilePath);
		BufferedWriter bw = null;
		OutputStreamWriter osw = null;
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(recordFile);
			osw = new OutputStreamWriter(fos,"utf-8");
			bw = new BufferedWriter(osw);
			//配送任务的标题是：序号|市民卡号|卡产品代码|物理类型|库存分类
			String content = "NO.|CITIZENNO|CARDPCODE|PHYSICTYPE|STOCKTYPE";
			bw.write(content);
			for(int i=0;i<paramList.size();i++){
				String[] subitemArray = paramList.get(i).split("#");
				String line = (i+1)+"|"+subitemArray[0]+"|"+subitemArray[1]+"|"+subitemArray[2]+"|"+subitemArray[3];
				logger.debug("line===>"+line);
				bw.write("\r\n");
				bw.write(line);
			}
			bw.flush();
		} catch (Exception e) {
			e.printStackTrace();
			throw new InventoryException("创建上缴卡片信息文件时，发生异常！请联系管理员！");
		} finally{
			if(bw!=null){
				try {
					bw.close();
				} catch (Exception e) {
					
					e.printStackTrace();
				}
			}
			if(osw!=null){
				try {
					osw.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if(fos!=null){
				try {
					fos.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 
	 */
	@SystemServiceLog(description = "查询配送任务信息")
	public DwzPage<DistributeInfo> queryDistributionRejectCardInfo(Map<String, String> map, int currentPage, int pageSize) {
		List<DistributeInfo> list = new ArrayList<DistributeInfo>();
		//数量，网点号，任务好的map
		Map<String,Object> rmap = new HashMap<String,Object>();
		//存放任务信息的对象
		//任务对象的属性是：市民卡号，卡名称，有效标志，制卡商，废卡原因，卡产品代码，制卡商代码，废卡原因代码，控制ID
		
		//检索对应路径下的配送任务文件
//		String targetPath = "D:\\resource\\distributeSuccessTask";
		String targetPath = REJECT_DISTRIBUTSUCCESS_PATH;
		String suffix = ".txt";
		List<Map<String,Object>> ditributionInfoList = parsePath2(targetPath,suffix,map);
		
		for(int i=0;i<ditributionInfoList.size();i++){
			DistributeInfo dInfo = new DistributeInfo();
			String distributeNo = (String)ditributionInfoList.get(i).get("taskNo");
			String branchNo = (String)ditributionInfoList.get(i).get("branchNo");
			String amount = String.valueOf(ditributionInfoList.get(i).get("amount"));
			String detailInfo = (String) ditributionInfoList.get(i).get("detailInfo");
			dInfo.setDistributeTaskNo(distributeNo);
			dInfo.setSourceBranchNo(branchNo);
			dInfo.setAmount(amount);
			dInfo.setDetailInfo(detailInfo);
			list.add(dInfo);
		}
		
		
		DwzPage<DistributeInfo> dp = new DwzPage<DistributeInfo>(currentPage, pageSize ,list.size());
		ListPageUtil<DistributeInfo> listPageUtil = new ListPageUtil<>(list,currentPage, pageSize);
		List<DistributeInfo> pagedList = listPageUtil.getPagedList();
		dp.setList(pagedList);
		return dp;
	}
	
	/**
	 * 解析路径，配送任务路径下的所有文档
	 * @param targetPath
	 * @param responsefilesuffix
	 * @param map
	 * @return
	 */
	@SystemServiceLog(description = "解析配送任务路径下的所有文档")
	private List<Map<String,Object>> parsePath2(String targetPath, String suffix, Map<String, String> map) {
		int amount = 0;
		/*1.获取配送号*/
		String distributeTaskNo = map.get("distributeTaskNo");
		/*2.获取网点号*/
		String sourceBranchNo = map.get("sourceBranchNo");
		/*3.记录文件号对应行数，即卡片数量*/
		Map<String,Object> amountMap = new HashMap<String,Object>();
		/*4.配送任务信息列表*/
		List<Map<String,Object>> ditributionInfoList = new ArrayList<Map<String,Object>>();
		/*5.txt文件中每行数据列表*/
		List<String> lineList = new ArrayList<String>();
		/*6.配送详细信息列表集合*/
	//	List<DistributeDetailInfo> detailInfoList = new ArrayList<DistributeDetailInfo>();
		String detailInfo = null;
		if((!"".equals(distributeTaskNo)&& distributeTaskNo!=null) && 
				(!"".equals(sourceBranchNo)&& sourceBranchNo!=null)){
			Map<String,Object> resultMap = new HashMap<String,Object>();
			String fileName = sourceBranchNo+distributeTaskNo;
			String filePath = targetPath+"\\"+fileName+suffix;
			logger.debug("文件的路径是==>"+filePath);
			File targetFile = new File(filePath);
			if(targetFile.exists()){
				lineList = readFile(targetFile);
				amount = lineList.size()-1;
				detailInfo = parseLineData(lineList);
				resultMap.put("taskNo", distributeTaskNo);
				resultMap.put("branchNo", sourceBranchNo);
				resultMap.put("amount", amount);
				resultMap.put("detailInfo", detailInfo);
				ditributionInfoList.add(resultMap);
			}
			
		}else{
			if(("".equals(distributeTaskNo)||distributeTaskNo==null) &&
					(!"".equals(sourceBranchNo)&&sourceBranchNo!=null)){
				String fileName = sourceBranchNo+"*"+suffix;
				File fileDir = new File(targetPath);
				FileFilter fileFilter = new WildcardFileFilter(fileName);
				File[] files = fileDir.listFiles(fileFilter);
				//对应文件名称，对应数量
				for(int i=0;i<files.length;i++){
					Map<String,Object> resultMap = new HashMap<String,Object>();
					String txtFileName = files[i].getName();
					int index = txtFileName.indexOf(".txt");
					String name = txtFileName.substring(0, index);
					logger.debug("文件名称为==>"+name);
					String branchNo = name.substring(0, 3);
					String taskNo = name.substring(3);
					File subFile = new File(targetPath+"\\"+txtFileName);
					if(subFile.exists()){
						lineList = readFile(subFile);
						amount = lineList.size()-1;
						detailInfo = parseLineData(lineList);
						resultMap.put("taskNo", taskNo);
						resultMap.put("branchNo", branchNo);
						resultMap.put("amount", amount);
						resultMap.put("detailInfo", detailInfo);
						ditributionInfoList.add(resultMap);
					}
					
				}
				
				
			}
			if((!"".equals(distributeTaskNo)&&distributeTaskNo!=null) &&
					("".equals(sourceBranchNo)||sourceBranchNo==null)){
				String fileName = "*"+distributeTaskNo+suffix;
				File fileDir = new File(targetPath);
				FileFilter fileFilter = new WildcardFileFilter(fileName);
				File[] files = fileDir.listFiles(fileFilter);
				//对应文件名称，对应数量
				for(int i=0;i<files.length;i++){
					Map<String,Object> resultMap = new HashMap<String,Object>();
					String txtFileName = files[i].getName();
					int index = txtFileName.indexOf(".txt");
					String name = txtFileName.substring(0, index);
					logger.debug("文件名称为==>"+name);
					String branchNo = name.substring(0, 3);
					String taskNo = name.substring(3);
					File subFile = new File(targetPath+"\\"+txtFileName);
					if(subFile.exists()){
						lineList = readFile(subFile);
						amount = lineList.size()-1;
						detailInfo = parseLineData(lineList);
						resultMap.put("taskNo", taskNo);
						resultMap.put("branchNo", branchNo);
						resultMap.put("amount", amount);
						resultMap.put("detailInfo", detailInfo);
						ditributionInfoList.add(resultMap);
					}
					
				}	
			}
			if(("".equals(distributeTaskNo)||distributeTaskNo==null) &&
					("".equals(sourceBranchNo)||sourceBranchNo==null)){
				File files = new File(targetPath);
				if(files.exists()){
					File[] fileArray = files.listFiles();
					for(int i=0;i<fileArray.length;i++){
						Map<String,Object> resultMap = new HashMap<String,Object>();
						String txtFileName = fileArray[i].getName();
						int index = txtFileName.indexOf(".txt");
						String name = txtFileName.substring(0, index);
						logger.debug("文件名称为==>"+name);
						String branchNo = name.substring(0, 3);
						String taskNo = name.substring(3);
						File subFile = new File(targetPath+"\\"+txtFileName);
						if(subFile.exists()){
							
							lineList = readFile(subFile);
							amount = lineList.size()-1;
							detailInfo = parseLineData(lineList);
							resultMap.put("taskNo", taskNo);
							resultMap.put("branchNo", branchNo);
							resultMap.put("amount", amount);
							resultMap.put("detailInfo", detailInfo);
							ditributionInfoList.add(resultMap);
						}
						
					}
				}
			}
			
		}
		return ditributionInfoList;
	}
	
	@SystemServiceLog(description = "获取信息")
	private String parseLineData(List<String> lineList) {
		List<DistributeDetailInfo> list = new ArrayList<DistributeDetailInfo>();
		String detailInfo = null;
		for(int i=1;i<lineList.size();i++){
			String lineInfo = lineList.get(i);
			String[] lineInfoArray = lineInfo.split("\\|");
			String citizencardno = lineInfoArray[0];
			String cardname = lineInfoArray[1];
			String validstatus = lineInfoArray[2];
			String companyname = lineInfoArray[3];
			String rejectcause = lineInfoArray[4];
			String cardcode = lineInfoArray[5];
			String companyno = lineInfoArray[6];
			String rejectcausecode = lineInfoArray[7];
			String cardcontrolID = lineInfoArray[8];
			logger.debug("市民卡号==>"+citizencardno);
			logger.debug("卡产品名称==>"+cardname);
			logger.debug("有效标志==>"+validstatus);
			logger.debug("制卡商名称==>"+companyname);
			logger.debug("废卡原因==>"+rejectcause);
			logger.debug("卡产品代码==>"+cardcode);
			logger.debug("制卡商代码==>"+companyno);
			logger.debug("废卡原因代码==>"+rejectcausecode);
			logger.debug("卡控制ID==>"+cardcontrolID);
			if(i==1){
				detailInfo = citizencardno+"&"+cardname+"&"+validstatus+"&"+companyname+"&"
			+rejectcause+"&"+cardcode+"&"+companyno+"&"+rejectcausecode+"&"+cardcontrolID;
			}else{
				detailInfo = detailInfo +"$"+citizencardno+"&"+cardname+"&"+validstatus+"&"+companyname+"&"
						+rejectcause+"&"+cardcode+"&"+companyno+"&"+rejectcausecode+"&"+cardcontrolID;
			}
		}
		return detailInfo;
	}


	/**
	* 读取txt文档的方法
	* @param targetFile
	* @return
	*/
	@SystemServiceLog(description = "读取txt文档")
	private List<String> readFile(File targetFile) {
		List<String> lineList = new ArrayList<String>();
		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		int count = 0;
		try {
			fis = new FileInputStream(targetFile);
			isr = new InputStreamReader(fis);
			br = new BufferedReader(isr);
			String line = "";
			while ((line = br.readLine()) != null ) {
				lineList.add(line);
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return lineList;
	}
	
	@Override
	public CooperationCompany CooperationCompanyMapper(String companies) {
		
		return ccm.queryCooperationCompanyByCompanyNo(companies);
	}

	@Override
	public void incomingRegisterService(String companies) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public PrimaryCardInfo queryPrimaryCode(String cardPrimaryCode) {
		PrimaryCardInfo cardInfo = pcim.queryPrimaryCardName(cardPrimaryCode);
		
		return cardInfo;
	}

	
	@SystemServiceLog(description = "获取出入库单号")
	@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
	private String getDetailNo() {
		String detailNo = sdm.queryStorageDetailNo();
		if("".equals(detailNo)||null==detailNo){
			detailNo = "MX00000001";
		}else{
			Integer dno = Integer.parseInt(detailNo.substring(2))+1;
			//取得的数字的长度
			int numLength = String.valueOf(dno).length();
			//判断取得的数字长度与字段长度，如果小于字段长度，那么说明字段的数字位是以0开头的，需要补位
			int addZero = detailNo.substring(2).length()-numLength;
			if(addZero>0){
				int len = detailNo.substring(2).length();
				detailNo = "MX"+String.format("%0" + len + "d", dno);
			}
			if(addZero==0){
				detailNo = "MX"+dno;
			}
		}
		return detailNo;
	}
	
	@Override
	@SystemServiceLog(description = "查询配送卡片信息")
	public List<CardControl> getDistributeList(List<String> taskLists,List<String> cardPCodeLists) {
		//信息返回的List
		List<CardControl> distributeInfoList = new ArrayList<CardControl>();
		distributeInfoList = stockdm.queryDistributeDetailByTaskNo(taskLists,cardPCodeLists);
		//logger.debug("结果集的长度是==>"+stockdm.queryDistributeDetailByTaskNo(taskLists,cardPCodeLists).size());
		return distributeInfoList;
	}

	/**
	 * 子模块：中心库配送到网点
	 * 配送的数据库操作
	 * @param serializeForm
	 * @return
	 * @throws ApplicationException 
	 */
	@SystemServiceLog(description = "配送数据库操作")
	@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
	public Map<String, Object> distributeRegistMethod(String serializeForm) throws InventoryException {
		
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");
		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		//返回的map
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//解析表单，按key，value键值对，装配
		Map<String,String> map = getKeyValueMap(serializeForm);
		logger.debug("配送表单map==>"+map);
		//装有卡产品名称的list
		List<String> cardPNameList = new ArrayList<String>();
		//装有每个批次卡数量的list
		List<Integer> cardAmountByTaskList = new ArrayList<Integer>();
		//装有每个批次供应商名称的list
		List<String> companyList = new ArrayList<String>();
		//每个批次的制卡号
		List<String> branchMakeNoList = new ArrayList<String>();
		//查询每个制卡批次对应的RBJM还是RJMK（空白卡和成品卡）
		Map<String,String> stockTypeAndBranchMap = new HashMap<String,String>();
		//每个产品代码对应的可配送数量，map
		Map<String,Integer> amountMap = new HashMap<String,Integer>();
		//每个任务的物理类型集合
		List<String> cardPhysicTypeList = new ArrayList<String>();
		
		//卡产品代码集合
		String cardPCodeString = map.get("cardpCode");
		logger.debug("cardPCodeString===>"+cardPCodeString);
		String[] cardPCodeArray = cardPCodeString.split("\\$");
		
		//卡产品名称集合
		String cardPNameString = map.get("cardPNameMap");
		logger.debug("cardPNameString===>"+cardPNameString);
		String[] cardPNameArray = cardPNameString.split("\\$");
		for(int i=0;i<cardPNameArray.length;i++){
			cardPNameList.add(cardPNameArray[i]);
		}
		
		//卡物理类型集合
		String cardPhysicTypeString = map.get("cardPhysicTypeByDistribute");
		logger.debug("cardPhysicTypeString===>"+cardPhysicTypeString);
		String[] cardPhysicTypeArray = cardPhysicTypeString.split("\\$");
		for(int i=0;i<cardPhysicTypeArray.length;i++){
			cardPhysicTypeList.add(cardPhysicTypeArray[i]);
		}
		
		//卡数量集合（所有批次的对应数量的集合，每个任务批次，一个数量）
		String amountByTask = map.get("cardAmount");
		logger.debug("amountByTask==>"+amountByTask);
		String[] amountByTaskArray = amountByTask.split("\\$");
		for(int j=0;j<amountByTaskArray.length;j++){
			cardAmountByTaskList.add(Integer.parseInt(amountByTaskArray[j]));
		}
		
		//制卡号集合
		String branchMakeNoString = map.get("branchMakeNo");
		logger.debug("branchMakeNoString==>"+branchMakeNoString);
		String[] branchMakeNoArray = branchMakeNoString.split("\\$");
		for(int k=0;k<branchMakeNoArray.length;k++){
			branchMakeNoList.add(branchMakeNoArray[k]);
		}
		
		//库存产品类型的集合，1代表rbjm,2代表rjmk
		List<ApplyBatchInfo> cardBatchObj = abim.queryCardTypeByMakeNoList(branchMakeNoList);
		for(int j=0;j<cardBatchObj.size();j++){
			logger.debug("cardBatchObj==>"+cardBatchObj.get(j));
			String taskType = cardBatchObj.get(j).getTaskType();
			String batchNo = cardBatchObj.get(j).getBatchMakeNo();
			if("2".equals(taskType)){
				stockTypeAndBranchMap.put(batchNo, "1");
			}
			if("1".equals(taskType)){
				stockTypeAndBranchMap.put(batchNo, "2");
			}
		}
		logger.debug("stockTypeAndBranchMap==>"+stockTypeAndBranchMap);
		//制卡商代码集合
		String companyNoString = map.get("companyNo");
		logger.debug("companyNoString==>"+companyNoString);
		String[] companyNoArray = companyNoString.split("\\$");
		for(int k=0;k<companyNoArray.length;k++){
			String companyName = ccm.queryCooperationCompanyByCompanyNo(companyNoArray[k]).getCompanyName();
			companyList.add(companyName);
		}		
		
		//卡数量,一个方法是查询数据库，另一个是计数，这里采用第二种方法
		for(int i=0;i<cardPCodeArray.length;i++){
			String cardPcodeAndType = cardPCodeArray[i]+"#"+stockTypeAndBranchMap.get(branchMakeNoList.get(i))+"#"+cardPhysicTypeList.get(i);
		/*	if(i==0){
				amountMap.put(cardPcodeAndType, Integer.parseInt(amountByTaskArray[i]));
			}*/
		//	if(i>0){
				Integer cardByCodeAmount = 0;
				if(amountMap.containsKey(cardPcodeAndType)){
					cardByCodeAmount = amountMap.get(cardPcodeAndType)+Integer.parseInt(amountByTaskArray[i]);
				}else{
					cardByCodeAmount = Integer.parseInt(amountByTaskArray[i]);	
				}
				amountMap.put(cardPcodeAndType, cardByCodeAmount);
		//	}
		}
		
		logger.debug("amountMap==>"+amountMap);
		logger.debug("cardPNameList==>"+cardPNameList.toString());
		
		//获取出库流水号
		//鱼洲杰 20180816增加以下 行
		String storageNo = inventoryRecordNoUtil.getStorageNo();
		logger.debug("storageNo===>"+storageNo);
		//String storageNo = map.get("storageNoByDis");
		//A.获取配送任务号 P+10位数字：6位年月日+4位顺序号
		//获取配送任务号
		String distributeTaskNo = inventoryRecordNoUtil.getDistributeTaskNo();
//		String distributeTaskNo = map.get("distributeTaskNoByDis");
		logger.debug("distributeTaskNo===>"+distributeTaskNo);
		//获取员工编号
		String operatorNo = map.get("distributeOperator");
		//获取操作网点编号
		String branchNo = map.get("distributeBranch");
		//获取任务编号
		String taskNos = map.get("cardTaskNo");
		logger.debug("taskNos===>"+taskNos);
		//获取总的数量
		String totalAmount = map.get("distributeAmount");
		//获取每个任务对应的数量
		String cardAmounts = map.get("cardAmount");
		// 任务列表taskNoList
		List<String> taskNoList = new ArrayList<String>();
		
		//解析每个任务编号对应的配送数量
		Map<String,String> cardAmountMap = new HashMap<String,String>();
		String[] cardAmountArray = cardAmounts.split("\\$");
		String[] taskNoArray = taskNos.split("\\$");
		int len = taskNoArray.length;
		
		//这边的数组，其实在前画面编辑传入的时候，可以使用不重复的list
		//这里的编辑是因为之前，要展示的表格信息是每个卡号的信息,所以,这里循环判断
		//如果表格的信息是按任务展示的信息，这个循环方法就不需要了
		for(int j=0;j<len;j++){
			if(j==0){
				cardAmountMap.put(taskNoArray[0], cardAmountArray[0]);
				taskNoList.add(taskNoArray[0]);
			}else{
				if(!cardAmountMap.containsKey(taskNoArray[j])){
					cardAmountMap.put(taskNoArray[j], cardAmountArray[j]);
					taskNoList.add(taskNoArray[j]);
				}
			}
		}
		logger.debug("每个任务对应的配送数量==>"+cardAmountMap);
		
		//20180818  惠国磊  增加以下   
		//  先查询出所有的任务号是否已经出库,如果已经不再库，抛出异常提示，
		//     您选择的项目有部分已经出库，请返回查询页面，重新操作！
		List<String> inStockStateList = stockdm.queryInStockStateByTaskNoList(taskNoList);
		for(int i=0;i<inStockStateList.size();i++){
			if("1".equals(inStockStateList.get(i))){
				//临时使用
				throw new InventoryException("信息有误,请返回刷新页面后继续操作！");
			}
		}
		
		//0.1 生成出库记录信息
		StorageReg storageRegObj = new StorageReg();
		// 0.1.1 属性的设置
		//   0.1.1.1 取画面传过来的值
		String curDate = DateAndStampUtil.getCurrentDate();
		String desBranchNo = map.get("applyBranchNoByDis");
		logger.debug("接收方的网点===>"+desBranchNo);
		//logger.debug("配送出库单号==>"+storageNo);
		logger.debug("配送任务号==>"+distributeTaskNo);
		logger.debug("配送出库总数量==>"+totalAmount);
		logger.debug("配送出库柜员编号==>"+operatorNo);
		logger.debug("配送出库网点编号==>"+branchNo);
		
		// 生成记录
		storageRegObj.setStorageNo(storageNo);
		storageRegObj.setBussinessNo("");
		// 出入库明细号编辑 
//		storageRegObj.setStorageDetailNo(storageDetailNo);
		storageRegObj.setAmount(Integer.parseInt(totalAmount));
		storageRegObj.setStorageMode("11");
		storageRegObj.setStorageType("1");
		//这里需要将reason再建一个表，入库原因及原因代码
		storageRegObj.setStorageReason("制卡任务配送出库");
				
		storageRegObj.setStorageDate(curDate);
		storageRegObj.setStorageStatus("1");
		storageRegObj.setRevocationDate("");
		storageRegObj.setRevocationOperatorNo("");
		storageRegObj.setRevocationBranchNo("");
		storageRegObj.setStartNo("");
		storageRegObj.setEndNo("");
		storageRegObj.setSourcePosition("0");
		storageRegObj.setDesPosition("2");
		//这里可以写制卡商代码
		storageRegObj.setSourceBranchNo("中心库房");
		//这里可以写中心库房网点编号
		storageRegObj.setDesBranchNo(desBranchNo);
		storageRegObj.setIsReceive("0");
		storageRegObj.setBothSeqNo("");
		storageRegObj.setDataInMode("");
		storageRegObj.setInputDate(curDate);
		storageRegObj.setRemark("");
		storageRegObj.setRevocationBussinessNo("");
		storageRegObj.setOperatorNo(operatorNo);
		storageRegObj.setOperateBranchNo(branchNo);
				
		srm.insert(storageRegObj);
		
		//0.2生成出入库明细表
		//20180529 惠国磊  每条任务一个明细信息
		//鱼洲杰20180817修改以下行
		String storageDetailNo = getDetailNo();
		logger.debug("配送出库明细号==>"+storageDetailNo);
		for(int i=0;i<taskNoList.size();i++){
			StorageDetail storageDetailObj = new StorageDetail();
			String taskNo = taskNoList.get(i);
			//String storageDetailNo = getDetailNo();
			//logger.debug("配送出库明细号==>"+storageDetailNo);
			storageDetailObj.setStorageDetailNo(storageDetailNo);
			storageDetailObj.setStorageNo(storageNo);
			storageDetailObj.setTaskNo(taskNo);
			storageDetailObj.setDistributeTaskNo(distributeTaskNo);
			Integer amountByPerTask = Integer.parseInt(cardAmountMap.get(taskNo));
			storageDetailObj.setAmount(amountByPerTask);
			sdm.insert(storageDetailObj);
			
			//重新计算入库明细号，并追加1
			storageDetailNo = getDetailNoNew(storageDetailNo);
			logger.debug("detailNo==>"+storageDetailNo);
		}
		
		//0.3更新库存汇总表
		String currentDate = DateAndStampUtil.getCurrentDate();
		//取出amountmap中的key和value,key是卡产品代码，value是每个卡产品出入库数量
		Set<Map.Entry<String,Integer>> entrySet = amountMap.entrySet();
		for(Map.Entry<String,Integer> entry:entrySet){
			//制卡商列表
			//companyList.add(entry.getKey());
			String[] cardPCodeAndstockType = entry.getKey().split("#");
			String cardPCode = cardPCodeAndstockType[0];
			String stockType = cardPCodeAndstockType[1];
			String cardPhysicType = cardPCodeAndstockType[2];
			
			StockSum ssObj = new StockSum();
			ssObj.setCardpCode(cardPCode);
			ssObj.setStockPosition("1");
			ssObj.setBranchNo(branchNo);
			ssObj.setOperatorAmount(entry.getValue());
			ssObj.setLastOperator(operatorNo);
			ssObj.setLastModDate(currentDate);
			ssObj.setCardStockType(stockType);
			ssObj.setCardPhysicType(cardPhysicType);
			
			//20180818 惠国磊 增加以下  更新前，先锁定该行数据
			String stockSumID = ssm.queryStockSumNoByCardPCode(ssObj);
			logger.debug("库存汇总ID==>"+stockSumID);
			String stockSumIDToUpdate = null;
			if("".equals(stockSumID) || stockSumID==null){
				//查找库存汇总表中最大的ID号
				String newID = null;
				String maxStockSumID = ssm.queryMaxStockSumID();
				Integer no = Integer.parseInt(maxStockSumID.substring(4))+1;
				//取得的数字的长度
				int numLength = String.valueOf(no).length();
				//判断取得的数字长度与字段长度，如果小于字段长度，那么说明字段的数字位是以0开头的，需要补位
				int addZero = maxStockSumID.substring(4).length()-numLength;
				if(addZero>0){
					int length = maxStockSumID.substring(4).length();
					newID = "KCHZ"+String.format("%0" + length + "d", no);
				}
				if(addZero==0){
					newID = "KCHZ"+no;
				}
				logger.debug("库存出入库汇总号是==>"+newID);
				ssObj.setStockSumId(newID);
				ssObj.setTotalNum(0);
				ssObj.setCurrNum(0);
				ssObj.setRealOutNum(0);
				ssObj.setOutSum(0);
				ssm.insertNewStockInfo(ssObj);
				stockSumIDToUpdate = newID;
			}else{
				stockSumIDToUpdate = stockSumID;
			}
			StockSum stockObj = ssm.queryStockSumBySumId(stockSumIDToUpdate);
			ssm.updateStockSumByDistribute(ssObj);
			
			//2.更新cd_stock_detail明细表
			//  2.1 根据制卡任务号查询库存汇总ID
			//查询库存汇总ID
			
			//  之前读取在库状态时，对应的行已经呗锁定
			StockDetail sdObj = new StockDetail();
			sdObj.setStockSumId(stockSumIDToUpdate);
			sdObj.setInStockStat("1");
			sdObj.setLstOutNo(storageNo);
			sdObj.setLstOutDate(currentDate);
			sdObj.setLstOutOperator(operatorNo);
			for(int m=0;m<taskNoList.size();m++){
				sdObj.setTaskNo(taskNoList.get(m));
				stockdm.updateStockDetailByDistribute(sdObj);
			}
		}
		
		
		
		List<String> citizenCardNoList = cdm.queryCitizenCardNoByDistributeOfCenter(taskNoList,"1");
		
		
		//卡过程表
		//查询出卡号
		Date currDate = new Date();
		List<CardManage> cardMagList = new ArrayList<CardManage>();
		List<CardControl> cardControlObjList = new ArrayList<CardControl>();
		for(int i=0;i<citizenCardNoList.size();i++){
			CardManage cme = new CardManage();
			String currProcId = UUID.randomUUID().toString().replace("-", "");
			cme.setProcessId(currProcId);
			cme.setApplyBranch(activeUser.getBranchName());
			cme.setApplyBranchNo(activeUser.getBranchNo());
			cme.setApplyDate(new Date());
			cme.setApplyTellerNo(activeUser.getUserNo().toString());
			cme.setBusinessNo("");
			cme.setProcessCode(CardContants.CARD_PROC_DIST);
			cme.setProcessName("配送出库");
			cme.setCitizenCardNo(citizenCardNoList.get(i));
			cme.setCardPosition(CardContants.CARD_POSITION_OTHER);
			cme.setCardStatus(CardContants.CARD_STATE_DISABLED);
		//	cme.setApplyWay("");// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
			cardMagList.add(cme);
			CardControl cardControlObj = cardControlMap.queryCardControlByCitizenCardNo(citizenCardNoList.get(i));
			cardControlObj.setCardPosition("9");
			cardControlObj.setLastDate(currDate);
			cardControlObj.setLastOperator(activeUser.getUserNo().toString());
			cardControlObj.setCurrProcId(currProcId);
			cardControlObj.setClaimStatus("07");
			cardControlObjList.add(cardControlObj);
		}
		cmm.batchInsert(cardMagList);
		
		//3.更新卡片管理信息
		cardControlMap.updateControlByDistribute(cardControlObjList);
		
		//打印单上的库存单号
		resultMap.put("storageNo", storageNo);
		//打印，数量
		resultMap.put("totalAmount", totalAmount);
		//打印，日期
		resultMap.put("curDate",curDate);
		//打印,网点
		resultMap.put("branchNo", branchNo);
		//打印，卡产品名称列表
		resultMap.put("cardPNameList", cardPNameList);
		//打印，制卡批号名称列表
		resultMap.put("makeCardNoList", branchMakeNoList);
		//打印，制卡商/来源网点
		resultMap.put("companyList", companyList);
		//打印，每个批次的数量列表
		resultMap.put("amountList", cardAmountByTaskList);
		//配送任务号，抬头标识
		resultMap.put("title", "配送清单"+distributeTaskNo);
		
		//打印预览清单
		
		createStoragePDF(resultMap);
		
		Map<String,Object> rMap = new HashMap<String,Object>();
		rMap.put("ipAddress", IP_ADDRESS);
		rMap.put("storageNo", storageNo);
		rMap.put("credential_type", "storage");
		rMap.put("title", resultMap.get("title"));
		logger.debug("distributeRegistMethod##########end");
		return rMap;
	}
	
	/**
	 * 解析画面的form序列参数,并装入map
	 * @param serializeForm
	 * @return
	 */
	@SystemServiceLog(description = "解析画面的form序列参数")
	private Map<String, String> getKeyValueMap(String serializeForm) {
		List<String> keyList = new ArrayList<String>();
		List<String> valueList = new ArrayList<String>();
		//map键值对，存放前画面的name和value
		Map<String,String> map = new HashMap<String,String>();
		//解析表单键值对,存入map中
		String[] formArray = serializeForm.split("&");
		for(int i=0;i<formArray.length;i++){
			logger.debug("form["+i+"]==>"+formArray[i]);
			String[] subItem = formArray[i].split("=");
			logger.debug("subItem的大小==>"+subItem.length);
			String itemName = subItem[0];
			keyList.add(itemName);
			String itemValue = "";
			if(subItem.length==2){
				itemValue = subItem[1];
			}
			valueList.add(itemValue);
			}
			logger.debug("keyList==>"+keyList.toString());
			logger.debug("valueList==>"+valueList.toString());
			String value = "";
			String key = "";
			//将画面传值key，value装入map中
			// 
			for(int j=0;j<valueList.size();j++){
				key = keyList.get(j);
				if(map.containsKey(key)){
					value = map.get(key)+"$"+valueList.get(j);
				}else{
					value = valueList.get(j);
				}
			map.put(key, value);
		}
		return map;
	}

	@Override
	@SystemServiceLog(description = "将form转化成map")
	public Map<String, String> getParamMap(String serilizeFormByCreateDis) {
		Map<String,String> rmap = getKeyValueMap(serilizeFormByCreateDis);
		return rmap;
	}
	/**
	 * 子模块：网点废卡配送并出库
	 * 功能：生成配送txt文件
	 */
	@Override
	@SystemServiceLog(description = "生成配送txt文件")
	public Map<String,String> createDistributeTaskFile(String checkedItems,String branchNo,String taskNo,String empNo) {
		Map<String,String> map = new HashMap<String,String>();
		//参数数据列表
		List<Map<String,Object>> paramList = new ArrayList<Map<String,Object>>();
		//controlId list
		List<String> cardControlIdList = new ArrayList<String>();
		//解析传入的参数
		//1.市民卡号  2.卡产品名称  3.有效标志  4.供应商名字 5.废卡原因代码 6.卡产品代码，7.供应商代码 8.废卡原因描述
		String[] paramArray = checkedItems.split("\\$");
		logger.debug("被解析的参数为==>"+paramArray[0]);
		for(int i=0;i<paramArray.length;i++){
			//选中的数据map,一条数据，一个map
			Map<String,Object> rmap = new HashMap<String,Object>();
			String[] subParam = paramArray[i].split("#");
			//将controlID装入List中
			cardControlIdList.add(subParam[8]);
			rmap.put("citizenCardNo", subParam[0]);
			rmap.put("cardName", subParam[1]);
			rmap.put("validStatus", subParam[2]);
			rmap.put("companyName", subParam[3]);
			rmap.put("rejectCause", subParam[4]);
			rmap.put("cardCode", subParam[5]);
			rmap.put("companyNo", subParam[5]);
			rmap.put("rejectCauseCode", subParam[6]);
			rmap.put("cardControlID", subParam[8]);
			logger.debug("被编辑的rmap==>"+rmap);
			paramList.add(rmap);
		}
		//将信息写入txt文本中，生成配送任务清单
		String fileName = createFile(paramList,paramArray,branchNo,taskNo);
		//修改被选中的卡片的状态
		
		map.put("fileName", fileName);
		return map;
	}
	
	/**
	 * 子模块：网点废卡配送并出库
	 * 功能:生成配送任务文档
	 * @param paramList
	 */
	@SystemServiceLog(description = "生成配送任务文档")
	private String createFile(List<Map<String, Object>> paramList,String[] paramArray,String branchNo,String taskNo) {
	//	String targetFilePath = "D:\\resource\\distributeTask";
		String targetFilePath = REJECT_DISTRIBUTETASK_PATH;
		String fileName = branchNo+taskNo+".txt";
		logger.debug("文件路径为==>"+targetFilePath+File.separator+fileName);
		//文件夹
		File file = new File(targetFilePath);
		if(!file.exists()){
			file.mkdir();
		}
		
		File targetFile = new File(targetFilePath+File.separator+fileName);
		int flag = 1;
		if(!targetFile.exists()){
			try {
				targetFile.createNewFile();
				flag = 0;
		} catch (IOException e) {
				e.printStackTrace();
			}
		}
		createTxt(targetFile,paramArray,flag);
		return fileName;
	}

	/**
	 * 子模块：网点废卡配送并出库
	 * 功能:生成txT文档
	 * @param file
	 * @param paramArray
	 * @param flag
	 */
	@SystemServiceLog(description = "生成txt文档")
	private void createTxt(File file, String[] paramArray,int flag) {
		FileOutputStream  fos = null;
		OutputStreamWriter osw= null; 
		BufferedWriter bw = null;
		logger.debug("flag===>"+flag);
		try {
			fos = new FileOutputStream(file,true);
			osw = new OutputStreamWriter(fos,"utf-8");
			bw = new BufferedWriter(osw);
			if(flag==0){
				StringBuffer sb =new StringBuffer();
				sb.append("citizenCardNo|cardName|validStatus|companyName|rejectCause|cardCode|companyNo|rejectCauseCode|cardControlId");
				bw.write(sb.toString());
				bw.write("\r\n");
			}
		 for(int j=0;j<paramArray.length;j++){
			String paramS = paramArray[j].replace("#", "|");
			logger.debug("被选中项目==>"+paramS.toString());
			bw.write(paramS);
			bw.write("\r\n");
		} 
		bw.flush();
		} catch (Exception e) {
			//异常后期自定义
			e.printStackTrace();
		}finally{
			if(bw!=null){
				try {
					bw.close();
				} catch (IOException e) {
					//异常后期自定义
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 子模块：网点废卡配送并出库
	 * 功能：查找配送任务的详细信息
	 * return rmap 装有txt文件的每行信息
	 */
	@Override
	@SystemServiceLog(description = "查询配送任务的详细信息")
	public Map<String, Object> queryDistributeInfo(String fileName) {
		String targetPath = null;
	//	targetPath = "D:\\resource\\distributeTask\\"+fileName;
		targetPath = REJECT_DISTRIBUTETASK_PATH+File.separator+fileName;
		logger.debug("targetPath==>"+targetPath);
		//解析文件，将txt中的信息装入list中
		List<Map<String,Object>> distributeDetailList = paesrFile(targetPath);
		Map<String,Object> rmap = new HashMap<String,Object>();
		rmap.put("distributeDetailList", distributeDetailList);
		return rmap;
	}
	
	/**
	 * 解析配送任务的文件，将每行数据编辑输出
	 * @param targetPath
	 * @return
	 */
	@SystemServiceLog(description = "解析配送任务的文件")
	private List<Map<String, Object>> paesrFile(String targetPath) {
		//返回的list
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		
		//读出的每一行内容列表
		List<String> lineList = new ArrayList<String>();
		File file = new File(targetPath);
		if(file.exists()){
			try {
				FileInputStream fis = new FileInputStream(file);
				InputStreamReader isr = new InputStreamReader(fis);
				BufferedReader br = new BufferedReader(isr);
				String line = "";
				while ((line = br.readLine()) != null) {
					lineList.add(line);	
		        }
				br.close();
				isr.close();
			    fis.close();
			} catch (Exception e) {
				//异常后续改正
				e.printStackTrace();
			} 
			String[] keyArray = lineList.get(0).split("\\|");
			for(int k = 1 ;k<lineList.size();k++){
				String line = lineList.get(k);
				String[] obj = line.split("\\|");
				//返回的List中的Map
				Map<String,Object> map = new HashMap<String,Object>();
				for(int n=0;n<obj.length;n++){
					map.put(keyArray[n], obj[n]);
				}
				list.add(map);
			}
		}
		return list;
	}

	/**
	 * 子模块：网点废卡配送并出库
	 * 功能：读出卡片信息
	 */
	@Override
	@SystemServiceLog(description = "读出卡片信息")
	public Map<String, Object> queryDistributeCardInfoByReject(Map<String, String> paramMap) {
		logger.debug("前画面传参==>"+paramMap);
		Map<String,Object> rmap = new HashMap<String,Object>();
		//存放页面信息map的list并装入rmap，返回前端页面
		List<Map<String,String>> rmapList = new ArrayList<Map<String,String>>();
		String citizenCardNo = paramMap.get("citizenCardNo");
		String cardCode = paramMap.get("cardCode");
		String fromDate = paramMap.get("fromDate");
		String toDate = paramMap.get("toDate");
		String branchNo = paramMap.get("branchNo");
		String cardControlIdList = paramMap.get("cardControlIdList");
		//解析list值
		List<String> idlist = new ArrayList<String>();
		if(cardControlIdList.indexOf("#")>=0){
			String[] cardControlList = cardControlIdList.split("#");
			for(int i=0;i<cardControlList.length;i++){
				idlist.add(cardControlList[i]);
			}
		}else if(!"".equals(cardControlIdList)&&cardControlIdList!=null){
			idlist.add(cardControlIdList);
		}
		logger.debug("idlist==>"+idlist.size());
		//查询废卡信息
		List<CardControl> resulList = cardControlMap.queryRejectCardInfoByBranchNo(citizenCardNo, cardCode, fromDate, toDate,branchNo,idlist);
		logger.debug("检索出的list==>"+resulList);
		//将页面的信息提取出来
		//1.卡号，2.卡产品代码，卡产品名称 3.制卡商代码  制卡商名称 4.卡有效标志 ，5.配送原因代码  6. 配送原因名称
		//卡产品代码，配送原因代码，制卡商代码
		List<String> cardCodeList = new ArrayList<String>();
		List<String> distributeCauseList = new ArrayList<String>();
		List<String> companyNoList = new ArrayList<String>();
		for(int i=0;i<resulList.size();i++){
			String cardPCODE = resulList.get(i).getCardData().getCardpCode();
			String companyCode = resulList.get(i).getCardTask().getCompanyNo();
			String logoutReason = resulList.get(i).getLogoutReason();
			cardCodeList.add(cardPCODE);
			distributeCauseList.add(logoutReason);
			companyNoList.add(companyCode);
		}
		//查询卡产品名称
		logger.debug("cardCodeList===>"+cardCodeList);
		List<CardProdunctDefinition> cardProductList = new ArrayList<CardProdunctDefinition>();
		if(cardCodeList.size()>0){
			cardProductList = cpdm.queryCardNameByCode(cardCodeList);
		}
		//查询卡供应商
		List<CooperationCompany> coperationCompany = new ArrayList<CooperationCompany>();
		if(companyNoList.size()>0){
			coperationCompany = coopcm.queryCooperationCompanyByCompanyNoList(companyNoList);
		}		
		//装入map(产品代码，产品名称)
		Map<String,String> cardProductMap = new HashMap<String,String>();
		Map<String,String> companyMap = new HashMap<String,String>();
		for(int j=0;j<cardProductList.size();j++){
			String name = cardProductList.get(j).getCardpName();
			String code = cardProductList.get(j).getCardpCode();
			cardProductMap.put(code, name);
		}
		//查询配送原因
		//查询制卡商名称
		for(int k=0;k<coperationCompany.size();k++){
			String companyCode = coperationCompany.get(k).getCompanyNo();
			String companyName = coperationCompany.get(k).getCompanyName();
			companyMap.put(companyCode, companyName);
		}
		rmap.put("resulList", resulList);
		rmap.put("cardProductCode", cardProductMap);
		rmap.put("companyCode", companyMap);
		logger.debug("cardProductCode==>"+cardProductMap);
		logger.debug("companyCode==>"+companyMap);
		return rmap;
	}
	
	/**
	 * 子模块：网点废卡配送并出库
	 * 功能：删除文件数据
	 */
	@Override
	@SystemServiceLog(description = "删除文件数据")
	public Map<String, Object> deleteItems(String deleteItems, String fileName,String controlID,String empNo) {
		Map<String,Object> rmap = null;
		List<Map<String,String>> itemList = new ArrayList<Map<String,String>>();
		//要删除的选项的卡号list
		List<String> deleteList = new ArrayList<String>();
		//要删除的选项的卡控制Id
		List<String> cardIdList = new ArrayList<String>();
		String[] deleteItemArray = deleteItems.split("\\$");
		String[] cardControlIdArray = controlID.split("\\$");
		for(int i=0;i<deleteItemArray.length;i++){
			deleteList.add(deleteItemArray[i]);
			cardIdList.add(cardControlIdArray[i]);
		}
		logger.debug("要删除的所有卡号==>"+deleteList.toString());
//		String fromPath = "D:\\resource\\distributeTask\\" + fileName + ".txt";
		String fromPath = REJECT_DISTRIBUTETASK_PATH + File.separator + fileName + ".txt";
//		String toPath = "D:\\resource\\distributeTask\\temple.txt";
		String toPath = REJECT_DISTRIBUTETASK_PATH + File.separator + "temple.txt";
		File fromFile = new File(fromPath);
		File toFile = new File(toPath);
		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		BufferedWriter bw = null;
		
		try {
			fis = new FileInputStream(fromFile);
			isr = new InputStreamReader(fis);
			br = new BufferedReader(isr);
			fos = new FileOutputStream(toFile);
			osw = new OutputStreamWriter(fos);
			bw = new BufferedWriter(osw);
			String line ="";
			while((line=br.readLine())!=null){
				String citizenNo = line.split("\\|")[0];
				if(!deleteList.contains(citizenNo)){
					bw.write(line);
					bw.write("\r\n");
				}
			}
			bw.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			if(br!=null){
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(bw!=null){
				try {
					bw.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					
				}
			}
		}
		
		//???先删除有没有风险
		//删除原先的文件 fromFile
		fromFile.delete();
		//重命名temple文件名，将所选中的要删除的卡号都删除后重新生成的一个文件
		toFile.renameTo(fromFile);
		
		//重新获得文件的清单
		List<Map<String,Object>> distributeDetailList = paesrFile(fromPath);
		rmap = new HashMap<String,Object>();
		rmap.put("distributeDetailList", distributeDetailList);
		return rmap;
	}

	@Override
	@SystemServiceLog(description = "保存配送的废卡信息")
	public Map<String, Object> saveDistributeInfo(String[] distributeItem) {
		Map<String,Object> rMap = new HashMap<String,Object>();
		List<Map<String,String>> itemList = new ArrayList<Map<String,String>>();
		for(int j=0;j<distributeItem.length;j++){
			String[] itemParam = distributeItem[j].split("#");
			Map<String,String> itemMap = new HashMap<String,String>();
			itemMap.put("citizenCardNo", itemParam[0]);
			itemMap.put("cardName", itemParam[1]);
			itemList.add(itemMap);
		}
		rMap.put("itemList", itemList);
		return rMap;
	}

	@Override
	@SystemServiceLog(description = "获取出入库流水号等信息")
	public Map<String, Object> getDistributeTaskInfo() {
		Map<String,Object> rmap = new HashMap<String,Object>();
		//获取最新的出入库流水号
//		String storageNo = inventoryRecordNoUtil.getStorageNo();
//		rmap.put("storageNo", storageNo);
		//获取当前日期
		String curDate = DateAndStampUtil.getCurrentDate();
		rmap.put("curDate", curDate);
//		logger.debug("网点配送的出库流水号==>"+storageNo);
		return rmap;
	}

	@Override
	@SystemServiceLog(description = "网点废卡出库登记")
	public Map<String, Object> submitDistributeTask(String serializeFormByDistribute) throws InventoryException {
		//返回的map
		Map<String, Object> resultMap = new HashMap<String,Object>();
		//卡产品名称列表集合
		List<String> cardPNameList = new ArrayList<String>();
		//卡产品对应的卡数量map
		Map<String,Integer> cardPNameAndAmount = new HashMap<String,Integer>();
		//卡产品对应的数量集合表
		List<String> amountList = new ArrayList<String>();
		//解析表单，按key，value键值对，装配
		Map<String,String> map = getKeyValueMap(serializeFormByDistribute);
		logger.debug("配送表单map==>"+map);
		//卡控制ID列表集合
		List<String> cardControlIdList = new ArrayList<String>();
		
		//1.修改卡控制表的状态
		String citizenCardNoArray = map.get("citizenCardNoByDis");
		String cardControlIdArray = map.get("cardControlIdByDis");
		String cardPNameArray = map.get("cardNameByDis");
		String operatorNo = map.get("empNo");
		logger.debug("citizenCardNoArray==>"+citizenCardNoArray);
		logger.debug("cardControlIdArray==>"+cardControlIdArray);
		logger.debug("cardPNameArray==>"+cardPNameArray);
		String[] controlIdArrays = cardControlIdArray.split("\\$");
		String[] cardPNameArrays = cardPNameArray.split("\\$");
		for(int i=0;i<controlIdArrays.length;i++){
			cardControlIdList.add(controlIdArrays[i]);
		}
		
		for(int i=0;i<cardPNameArrays.length;i++){
			Integer amount = 1;
			String cardPName = cardPNameArrays[i];
			if(cardPNameAndAmount.containsKey(cardPName)){
				amount = cardPNameAndAmount.get(cardPName)+1;
			}else{
				cardPNameList.add(cardPName);
				amount = 1;
			}
			cardPNameAndAmount.put(cardPName, amount);	
		}
		logger.debug("cardPNameAndAmount===>"+cardPNameAndAmount);
		for(int j=0;j<cardPNameList.size();j++){
			String cardPName = cardPNameList.get(j);
			String amount = String.valueOf(cardPNameAndAmount.get(cardPName));
			amountList.add(amount);
		}
		
		//先查询要出库的卡片状态是否在库
		// 如果不再库，那么抛出异常
		List<String> positionStatusByControlId = cardControlMap.queryCardPositionByControlId(cardControlIdList);
		for(int i=0;i<positionStatusByControlId.size();i++){
			if(!"2".equals(positionStatusByControlId.get(i))){
				throw new InventoryException("信息有误,请返回刷新页面后重新操作！");
			}
		}
		cardControlMap.updateControlByRejectDistribute(cardControlIdList,operatorNo);
		
		//1.生成出入库记录
		
		// 1.2 获取新的入库号，并锁住该行数据
		String storageNo = inventoryRecordNoUtil.getStorageNo();
		//String storageDetailNo
		String amount = map.get("cardAmount");
		String fromBranchNo = map.get("branchNo");
		String distributeTaskNo = map.get("distributeTaskNo");
		String curDate = map.get("distributeDate");
		
		StorageReg storageRegObj = new StorageReg();
		
		logger.debug("网点配送出库流水号==>"+storageNo);
		logger.debug("网点配送数量==>"+amount);
		logger.debug("网点配送起始网点编号==>"+fromBranchNo);
		logger.debug("网点配送当前日期==>"+curDate);
		
		storageRegObj.setStorageNo(storageNo);
		storageRegObj.setStorageDetailNo("");
		storageRegObj.setBussinessNo("");
		storageRegObj.setAmount(Integer.parseInt(amount));
		storageRegObj.setStorageMode("15");
		storageRegObj.setStorageType("1");
		storageRegObj.setStorageReason("废卡配送");
		storageRegObj.setStorageDate(curDate);
		storageRegObj.setStorageStatus("1");
		storageRegObj.setRevocationBussinessNo("");
		storageRegObj.setRevocationDate("");
		storageRegObj.setRevocationOperatorNo("");
		storageRegObj.setRevocationBranchNo("");
		storageRegObj.setStartNo("");
		storageRegObj.setEndNo("");
		storageRegObj.setSourcePosition("2");
		storageRegObj.setDesPosition("0");
		storageRegObj.setSourceBranchNo(fromBranchNo);
		storageRegObj.setDesBranchNo("10000000");
		storageRegObj.setIsReceive("0");
		storageRegObj.setDataInMode("");
		storageRegObj.setOperateBranchNo(fromBranchNo);
		storageRegObj.setOperatorNo(operatorNo);
		storageRegObj.setInputDate(curDate);
		storageRegObj.setRemark("");
		logger.debug("storageRegObj===>"+storageRegObj);
		srm.insert(storageRegObj);
		
		
		//生成出入库明细记录
		StorageDetail storageDetail = new StorageDetail();
		String storageDetailNo = getDetailNo();
		String distributeNo = fromBranchNo+map.get("distributeTaskNo");
		storageDetail.setStorageNo(storageNo);
		storageDetail.setStorageDetailNo(storageDetailNo);
		storageDetail.setAmount(Integer.parseInt(amount));
		storageDetail.setDistributeTaskNo(distributeNo);
		logger.debug("storageDetailObj===>"+storageDetail);
		sdm.insert(storageDetail);
		
		//更新库存汇总表
		//取出卡产品代码，编辑map（卡产品代码，数量）
		Map<String,Integer> cardAmountMap = new HashMap<String,Integer>();
		String[] cardCodeArry = map.get("cardCodeByDis").split("\\$");
		for(int i =0;i<cardCodeArry.length;i++){
			if(cardAmountMap.containsKey(cardCodeArry[i])){
				int count = cardAmountMap.get(cardCodeArry[i]);
				cardAmountMap.put(cardCodeArry[i], count+1);
			}else{
				cardAmountMap.put(cardCodeArry[i], 1);
			}
		}
		//遍历map，并更新
		Set<Map.Entry<String,Integer>> entrySet = cardAmountMap.entrySet();
		
		String ID = stockdm.queryMaxDetailId();
		if("".equals(ID)||null==ID){
				ID = "1";
		}
		int id = Integer.parseInt(ID)+1;
		for(Map.Entry<String,Integer> entry:entrySet){
			StockSum ssObj = new StockSum();
			ssObj.setCardpCode(entry.getKey());
            CardProdunctDefinition cpd= cpdm.queryCardCode(entry.getKey());
			ssObj.setCardpName(cpd.getCardpName());
			ssObj.setStockPosition("2");
			ssObj.setBranchNo(fromBranchNo);
			String stockSumID = ssm.queryStockSumNoByCardPCode(ssObj);
			logger.debug("库存汇总ID==>"+stockSumID);
			String stockSumIDToUpdate = null;
			if("".equals(stockSumID) || stockSumID==null){
				//查找库存汇总表中最大的ID号
				String newID = null;
				String maxStockSumID = ssm.queryMaxStockSumID();
				Integer no = Integer.parseInt(maxStockSumID.substring(4))+1;
				//取得的数字的长度
				int numLength = String.valueOf(no).length();
				//判断取得的数字长度与字段长度，如果小于字段长度，那么说明字段的数字位是以0开头的，需要补位
				int addZero = maxStockSumID.substring(4).length()-numLength;
				if(addZero>0){
					int len = maxStockSumID.substring(4).length();
					newID = "KCHZ"+String.format("%0" + len + "d", no);
				}
				if(addZero==0){
					newID = "KCHZ"+no;
				}
				logger.debug("库存出入库汇总号是==>"+newID);
				ssObj.setStockSumId(newID);
				ssObj.setTotalNum(0);
				ssObj.setCurrNum(0);
				ssObj.setRealOutNum(0);
				ssObj.setOutSum(0);
				ssm.insertNewStockInfo(ssObj);
				stockSumIDToUpdate = newID;
			}else{
				stockSumIDToUpdate = stockSumID;
			}
			StockSum stockSumObjTemp = ssm.queryStockSumBySumId(stockSumIDToUpdate);
			
			ssObj.setOperatorAmount(entry.getValue());
			ssObj.setLastOperator(operatorNo);
			ssObj.setLastModDate(curDate);
			ssm.updateStockSumByDistributeToCenter(ssObj);
			
			String stockSumid = ssm.queryStockSumNoByCardPCode(ssObj);
			
			
			StockDetail stockDetail = new StockDetail();
			stockDetail.setStockSumId(stockSumid);
			stockDetail.setStockDetailId(id);
			stockDetail.setTaskNo(distributeNo);
			stockDetail.setMakecardReturnNo("");
			stockDetail.setItemAttrVal03("");
			stockDetail.setItemAttrVal04("");
			stockDetail.setItemAttrVal05("");
			stockDetail.setAmount(entry.getValue());
			stockDetail.setInStockStat("1");
			stockDetail.setLstInNo("");
			stockDetail.setLstOutNo(storageNo);
			stockDetail.setLstInDate("");
			stockDetail.setLstOutDate(DateAndStampUtil.getCurrentDate());
			stockDetail.setLstInOperator("");
			stockDetail.setLstOutOperator(operatorNo);
			stockDetail.setFileDate("");
			stockDetail.setFileFlag("");
			logger.debug("stockDetail===>"+stockDetail.toString());
			stockdm.insert(stockDetail);
			id++;
		}
				
		//移动任务文件至目标路径
	//	String targetPath = "D:\\resource\\distributeSuccessTask";
		String targetPath = REJECT_DISTRIBUTSUCCESS_PATH;
		String fileName = fromBranchNo + distributeTaskNo;
		String sourcePath = REJECT_DISTRIBUTETASK_PATH+File.separator+fileName+".txt";
		logger.debug("要移动的文件路径==>"+sourcePath);
		FileUtil.moveTotherFolders(sourcePath,targetPath);
//		File file = new File("D:\\resource\\distributeTask\\");
		File file = new File(REJECT_DISTRIBUTETASK_PATH+File.separator);
		//把task任务路径下的所有的临时文件都删掉
		//可以整个一起删
		if(file.exists()){
			file.delete();
			
		}
		
		//装在打印需要的参数
		//入库号
		resultMap.put("storageNo", storageNo);
		//网点号
		resultMap.put("branchNo", fromBranchNo);
		//入库总数量(因为这里是只选择一项，数量暂时这么编辑，后期需要改正)
		resultMap.put("totalAmount", amount);
		//入库日期
		resultMap.put("curDate", DateAndStampUtil.getCurrentDate());
		//清单明细抬头
		resultMap.put("title", "废卡上缴出库");
		//卡产品名称列表
		resultMap.put("cardPNameList", cardPNameList);
		//制卡批号列表
		resultMap.put("makeCardNoList", "");
		//制卡商名称列表
		resultMap.put("companyList", "");
		//每个批号的数量列表
		resultMap.put("amountList", amountList);
		//凭证类型
		resultMap.put("credential_type", "storage");
		
		return resultMap;
	}


	@Override
	@SystemServiceLog(description = "解析查询配送任务画面")
	public Map<String, Object> parseCheckItem(String checkedItem) {
		Map<String,Object> map = new HashMap<String,Object>();
		String[] itemArray = checkedItem.split("#");
		String sourceBranchNo = itemArray[0];
		String distributeNo = itemArray[1];
		String distributeAmount = itemArray[2];
		String detailInfo = itemArray[3];
		logger.debug("所选中的配送号==>"+distributeNo);
		logger.debug("所选中的网点号==>"+sourceBranchNo);
		logger.debug("所选中的配送数量==>"+distributeAmount);
		logger.debug("所选中的配送明细==>"+detailInfo);
		
		//解析明细信息
		List<DistributeDetailInfo> detailList = new ArrayList<DistributeDetailInfo>();
		detailList = parseDetailInfo(detailInfo);
		map.put("distributeNo", distributeNo);
		map.put("sourceBranchNo", sourceBranchNo);
		map.put("distributeAmount", distributeAmount);
		map.put("detailList", detailList);
		
		//获取入库流水号
		String storageNo = inventoryRecordNoUtil.getStorageNo();
		map.put("storageNo", storageNo);
		return map;
	}

	@SystemServiceLog(description = "获取文件信息")
	private List<DistributeDetailInfo> parseDetailInfo(String detailInfo) {
		List<DistributeDetailInfo> list = new ArrayList<DistributeDetailInfo>();
		if(detailInfo.split("\\$").length>0){
			String[] detailInfoArray = detailInfo.split("\\$");
			for(int i=0;i<detailInfoArray.length;i++){
				DistributeDetailInfo dDetailInfo = new DistributeDetailInfo();
				dDetailInfo = packDetailMap(detailInfoArray[i],dDetailInfo);
				list.add(dDetailInfo);
			}
		}
		logger.debug("list的大小==>"+list.size());
		return list;
	}

	@SystemServiceLog(description = "获取信息")
	private DistributeDetailInfo packDetailMap(String string, DistributeDetailInfo dDetailInfo) {
		String[] items = string.split("&");
		for(int m=0;m<items.length;m++){
			String citizencardno = items[0];
			String cardname = items[1];
			String validstatus = items[2];
			String companyname = items[3];
			String rejectcause = items[4];
			String cardcode = items[5];
			String companyno = items[6];
			String rejectcausecode = items[7];
			String cardcontrolID = items[8];
			logger.debug("市民卡号==>"+citizencardno);
			logger.debug("卡产品名称==>"+cardname);
			logger.debug("有效标志==>"+validstatus);
			logger.debug("制卡商名称==>"+companyname);
			logger.debug("废卡原因==>"+rejectcause);
			logger.debug("卡产品代码==>"+cardcode);
			logger.debug("制卡商代码==>"+companyno);
			logger.debug("废卡原因代码==>"+rejectcausecode);
			logger.debug("卡控制ID==>"+cardcontrolID);
			dDetailInfo.setCitizenCardNo(citizencardno);
			dDetailInfo.setCardName(cardname);
			dDetailInfo.setValidStatus(validstatus);
			dDetailInfo.setCompanyName(companyname);
			dDetailInfo.setCardCode(cardcode);
			dDetailInfo.setCompanyCode(companyno);
			dDetailInfo.setRejectCause(rejectcause);
			dDetailInfo.setRejectCauseCode(rejectcausecode);
			dDetailInfo.setCardControlID(cardcontrolID);
		}
		return dDetailInfo;
	}


	@Override
	@SystemServiceLog(description = "网点配送到中心库接收操作")
	public void dbExecute(String serializeFormByRejIncoming) {
		//解析form表单，装入map
		Map<String,String> map = getKeyValueMap(serializeFormByRejIncoming);
		logger.debug("入库登记的所有信息==>"+map);
		
		//0.更新原来的配送出库状态
		String distributeNo = map.get("distributeTaskNoByReceive");
		
		String originalStorageNo = sdm.queryStorageNoByTaskNo(distributeNo);
		logger.debug("查询出来的出库单号==>"+originalStorageNo);
		srm.updateStorageNoByDistribute(originalStorageNo);
		
		//1.生成入库明细信息
		String storageDetailNo = getDetailNo();
		String storageNoByReceive = map.get("storageNoByReceive");
		String amount = map.get("amountByReceive");
		
		logger.debug("配送中心库入库号==>"+storageDetailNo);
		logger.debug("配送中心库入库明细号==>"+storageNoByReceive);
		logger.debug("配送中心库入库数量==>"+amount);
		logger.debug("配送中心库配送任务号==>"+distributeNo);
		StorageDetail storageDetailObj = new StorageDetail();
		storageDetailObj.setAmount(Integer.parseInt(amount));
		storageDetailObj.setStorageNo(storageNoByReceive);
		storageDetailObj.setStorageDetailNo(storageDetailNo);
//		storageDetailObj.setItemAttrVal02(distributeNo);
		sdm.insert(storageDetailObj);
		
		//2.生成入库信息
		String empNo = map.get("empNoByReceive");
		String desBranchNo = map.get("branchNoByReceive");
		String sourceBranchNo = map.get("sourceBranchNoByReceive");
		logger.debug("废卡入库操作员工号==>"+empNo);
		logger.debug("废卡入库操作网点号==>"+desBranchNo);
		logger.debug("废卡入库来源网点号==>"+sourceBranchNo);
		String currentDate = DateAndStampUtil.getCurrentDate();
		StorageReg sorageRegObj = new StorageReg();
		
		sorageRegObj.setStorageNo(storageNoByReceive);
		sorageRegObj.setStorageDetailNo(storageDetailNo);
		sorageRegObj.setBussinessNo("");
		sorageRegObj.setAmount(Integer.parseInt(amount));
		sorageRegObj.setStorageMode("03");
		sorageRegObj.setStorageType("0");
		sorageRegObj.setStorageReason("废卡入库");
		sorageRegObj.setStorageDate(currentDate);
		sorageRegObj.setStorageStatus("1");
		sorageRegObj.setRevocationBussinessNo("");
		sorageRegObj.setRevocationDate("");
		sorageRegObj.setRevocationOperatorNo("");
		sorageRegObj.setRevocationBranchNo("");
		sorageRegObj.setStartNo("");
		sorageRegObj.setEndNo("");
		sorageRegObj.setSourcePosition("2");
		sorageRegObj.setDesPosition("0");
		sorageRegObj.setSourceBranchNo(sourceBranchNo);
		sorageRegObj.setDesBranchNo(desBranchNo);
		sorageRegObj.setIsReceive("");
		sorageRegObj.setDataInMode("");
		sorageRegObj.setOperateBranchNo(desBranchNo);
		sorageRegObj.setOperatorNo(empNo);
		sorageRegObj.setInputDate(currentDate);
		sorageRegObj.setRemark("");
		srm.insert(sorageRegObj);
		
		//3.更新库存表
		//如果库存汇总表中没有该产品和网点对应的信息，生成一条数据
		Map<String,Integer> amountMap = new HashMap<String,Integer>();
		String[] cardCodeArry = map.get("cardCodeByInco").split("\\$");
		for(int i =0;i<cardCodeArry.length;i++){
			if(amountMap.containsKey(cardCodeArry[i])){
				int count = amountMap.get(cardCodeArry[i]);
				amountMap.put(cardCodeArry[i], count+1);
			}else{
				amountMap.put(cardCodeArry[i], 1);
			}
		}
		logger.debug("卡产品对应的数量==>"+amountMap);
		//遍历map，并更新
		Set<Map.Entry<String,Integer>> entrySet = amountMap.entrySet();
		for(Map.Entry<String,Integer> entry:entrySet){
			StockSum ssObj = new StockSum();
			ssObj.setCardpCode(entry.getKey());
			ssObj.setStockPosition("1");
			ssObj.setBranchNo(desBranchNo);
			ssObj.setOperatorAmount(entry.getValue());
			ssObj.setLastOperator(empNo);
			ssObj.setLastModDate(currentDate);
			ssm.updateStockSumByDistribute(ssObj);
		}
		
		//4.更新库存明细表
		//暂时不更新，后续
		
		//5.更新卡管理表
		//暂时不更新,后续
		
		//6.转移文件,已入库
		String targetPath = "D:\\resource\\distributeIncomed";
		String fileName = sourceBranchNo + distributeNo;
		String sourcePath = "D:\\resource\\distributeSuccessTask\\"+fileName+".txt";
		logger.debug("要移动的文件路径==>"+sourcePath);
		FileUtil.moveTotherFolders(sourcePath,targetPath);
	}	


	@Override
	public List<StorageRegRecVo> querycardReceiving(String taskNo) {
		//根据任务编号查询网点接收配送信息
		return srm.queryCardReceivingByTaskNo(taskNo);
	}

	@Override
	public StorageReg queryStorageRegByStorageNo(String storageNo) {
		
		return srm.queryStorageRegByStorNo(storageNo);
	}
	
	@SystemServiceLog(description = "入库撤销")
	public void queryStorageReg(StorageReg sr) {
		StockDetail sd=stockdm.queryStockDetailByStorNo(sr.getStorageNo());
		StockSum ss=ssm.queryStockSumByStorNo(sd.getStockSumId());
		logger.info("########start==>"+sd.toString()+ss.toString());
		ss.setTotalNum(ss.getTotalNum()-sd.getAmount());
		ss.setCurrNum(ss.getCurrNum()-sd.getAmount());
		ss.setLastModDate(gettime());
		logger.info("########显示日期==>"+ss.getLastModDate());
		ss.setLastOperator("yzj");
		ssm.update(ss);//更新库存汇总表
		
		sr.setStorageStatus("2");
		sr.setRevocationDate(gettime());
		sr.setRevocationOperatorNo("yzj");
		sr.setRevocationBranchNo("网点编号001");
		//srm.update(sr);//更新出入库登记表
		
	}
	 public String gettime() {//将当前日期转化为String
		Date date = new Date();
		String dateStr = new SimpleDateFormat("yyyy-MM-dd ").format(date);
		return dateStr;
		}

	@Override
	public StockDetail queryStockDetailByStorageNo(String storageNo) {
		
		return stockdm.queryStockDetailByStorNo(storageNo);
	}
	
	
	/**
	 * 编号：5-1-1
	 * 功能：查询出库信息
	 */
	@SystemServiceLog(description = "查询出库信息")
	public DwzPage<StorageRegRecVo> queryOutgoingRevcotion(Map<String,String> map, Integer currentPage, Integer numPerPage) {
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");
		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		String storageNo = map.get("storageNo");
		String storageMode = map.get("storageMode");
		String storageDateFrom = map.get("storageDateFrom");
		String storageDateTo = map.get("storageDateTo");
		String branchNo = map.get("branchNo");
		String empNo = map.get("empNo");
		logger.debug("画面的storageNo==>"+storageNo);
		logger.debug("画面的storageMode==>"+storageMode);
		logger.debug("画面的storageDate==>"+storageDateFrom);
		logger.debug("画面的storageDate1==>"+storageDateTo);
		logger.debug("画面的branchNo==>"+branchNo);
		logger.debug("画面的empNo==>"+empNo);
		if(branchNo==null){
			branchNo=activeUser.getBranchNo();
		}
		Integer startLine = (currentPage-1)*numPerPage;
		//20180928鱼洲杰修改以下行
		Integer endLine = numPerPage;
		List<StorageRegRecVo> storageRegList= srm.queryOutRevocation(storageNo, storageMode, storageDateFrom, storageDateTo,branchNo,startLine,endLine);
		//页面列表信息
		Integer totalCount =srm.queryOutRevocationNumber(storageNo, storageMode, storageDateFrom, storageDateTo, branchNo);
		DwzPage<StorageRegRecVo> dp = new DwzPage<StorageRegRecVo>(currentPage ,numPerPage, totalCount);
		dp.setList(storageRegList);
		return dp;
	}

	@Override
	public StorageRegVo queryOutgoRevoction(String storageNo) {
		return srm.queryOutgoRevoctionByStorageNo(storageNo);
	}

	@Override
	@SystemServiceLog(description = "出库撤销登记")
	public void OutgoingRevocation(StorageRegVo srv) {
		StockSum ss =ssm.queryStockSumByStorNo(srv.getStockSumId());
		ss.setCurrNum(ss.getCurrNum()+srv.getAmount());
		ss.setOutSum(ss.getOutSum()-srv.getAmount());
		ss.setLastModDate(DateAndStampUtil.getCurrentDate());
		ss.setLastOperator("yzj1");
		//ssm.update(ss);//更新库存汇总表
		logger.debug("库存汇总==>"+ss);
		
		StockDetail sd=stockdm.queryStockDetailByTakNoANDStockSumId(srv.getStockSumId(),srv.getTaskNo());
		sd.setAmount(Integer.valueOf(ss.getCurrNum()));
		sd.setInStockStat("0");
		//stockdm.update(sd);//更新库存明细表
		logger.debug("库存明细==>"+sd);
		
		StorageReg sr=srm.queryStorageRegByStorNo(srv.getStorageNo());
		sr.setStorageStatus("2");
		sr.setRevocationDate(DateAndStampUtil.getCurrentDate());
		sr.setRevocationOperatorNo("yzj");
		sr.setRevocationBranchNo("007");
		//srm.update(sr);//更新出入库登记表
		logger.debug("出入库登记==>"+sr);
	}

	/**
	 * 通过 市民卡号查询卡信息
	 */
	@SystemServiceLog(description = "通过市民卡号查询卡信息")
	public CardData queryCardDataByCitizenNo(String citizenCardNo) {
		CardData cardDataInfo = cdm.queryCardDataByCitizenCardNoAtReadBlank(citizenCardNo);
		if(cardDataInfo!=null){
			logger.debug(citizenCardNo+"卡号的信息是===>"+cardDataInfo.toString());
		}
		return cardDataInfo;
	}

	/**
	 * 查询空白卡/成品卡上缴记录
	 */
	@SystemServiceLog(description = "查询空白卡/成品卡上缴记录")
	public DwzPage<Map<String,String>> getBlankAndFinishCardReceiving(Map<String, String> map, Integer currentPage,
			Integer numPerPage) {
		String distributeTaskNo = map.get("distributeTaskNo");
		logger.debug("空白卡/成品卡配送任务号===>"+distributeTaskNo);
		//读取指定目录下的文件信息
//		String filePath = "D:\\Apache24\\htdocs\\qzsmk\\resource\\blankAndRejectTaskFile\\"+distributeTaskNo+".txt";
		String filePath = BLANK_REJECT_TASK_PATH + File.separator + distributeTaskNo+".txt";
		//文件中每行内容列表
		List<Map<String,String>> lineList = new ArrayList<Map<String,String>>();
		
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");
		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		
		//查询该任务号对应的接收标志是否是0，0：未接收，1：已接收
		String receivingFlag = srm.queryStorageNoReceivingFlag(distributeTaskNo,activeUser.getBranchNo());
		if("0".equals(receivingFlag)||"".equals(receivingFlag)){
			File file = new File(filePath);
			FileInputStream fis = null;
			InputStreamReader isr = null;
			BufferedReader br = null;
			String line = null;
			try {
				fis = new FileInputStream(file);
				isr = new InputStreamReader(fis,"utf-8");
				br = new BufferedReader(isr);
				while((line=br.readLine())!=null){
					String[] itemArray = line.split("\\|");
					//市民卡号,卡产品代码的map
					Map<String,String> lineMap = new HashMap<String,String>();
					lineMap.put("citizenCardNo",itemArray[1]);
					lineMap.put("cardpCode",itemArray[2]);
					lineMap.put("cardType",itemArray[3]);
					lineMap.put("stockType",itemArray[4]);
					logger.debug("lineMap===>"+lineMap);
					lineList.add(lineMap);
				}
			} catch (Exception e) {

				e.printStackTrace();
			}finally{
				if(br!=null){
					try {
						br.close();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(isr!=null){
					try {
						isr.close();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(fis!=null){
					try {
						fis.close();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		
		
		//分页处理
		DwzPage<Map<String,String>> dp = new DwzPage<Map<String,String>>(currentPage, numPerPage ,lineList.size()-1);
		ListPageUtil<Map<String,String>> listPageUtil = new ListPageUtil<>(lineList,currentPage, numPerPage);
		List<Map<String,String>> pagedList = listPageUtil.getPagedList();
		dp.setList(pagedList);
		logger.debug("配送信息==>"+pagedList);
		return dp;
	}

	/**
	 * 空白卡片/成品卡片登记处理
	 */
	@SystemServiceLog(description = "空白卡/成品卡入库登记处理")
	public Map<String, Object> BlankAndRejectCardReceivingRegist(String checkedeParam,String storageModeByTurnIn){
		//市民卡号列表集合
		List<String> citizenNoList = new ArrayList<String>();
		//卡产品代码列表集合
		List<String> cardPCodeList = new ArrayList<String>();
		//卡产品物理类型库存类型，对应的数量
		Map<String,Integer> cardCodeAndTypeAmountMap = new HashMap<String,Integer>();
		//卡产品名称列表集合
		List<String> cardPNameList = new ArrayList<String>();
		//卡产品(卡类型代码，卡产品名称)map
		Map<String,String> cardProductMap = new HashMap<String,String>();
		//卡产品(卡类型代码，卡产品名称)map
		Map<String,String> cardCodeAndCardNameMap = new HashMap<String,String>();
		//(卡物理类型，类型名称)map
		Map<String,String> cardTypeCodeAndNameMap = new HashMap<String,String>();
		//卡产品对应的数量列表集合
		List<Integer> amountList = new ArrayList<Integer>();
		//返回的打印用参数map
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String distributeTaskNo = null;
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");
		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		//解析传递过来的参数,
		//20181120 增加卡类型
		String[] checkedeParamArray = checkedeParam.split("\\$");
		for(int i=0;i<checkedeParamArray.length;i++){
			String[] itemArray = checkedeParamArray[i].split("#");
			Integer amount = 0;
			distributeTaskNo = itemArray[0];
			String citizenCardNoArray = null;
			String citizenCardNo = itemArray[1];
			String cardpCode = itemArray[2];
			String cardPhysicType = itemArray[3];
			String stockType = itemArray[4];
			String key = cardpCode+"#"+cardPhysicType+"#"+stockType;
			citizenNoList.add(citizenCardNo);
			cardPCodeList.add(cardpCode);
			if(cardCodeAndTypeAmountMap.containsKey(key)){
				amount = cardCodeAndTypeAmountMap.get(key) + 1;				
			}else{
				amount = 1;
			}
			cardCodeAndTypeAmountMap.put(key, amount);
		}
		logger.debug("cardCodeAndTypeAmountMap==>"+cardCodeAndTypeAmountMap);
		//出去重复的市民卡号
		HashSet<String> codeSet = new HashSet<String>(cardPCodeList);
		cardPCodeList.clear();
		cardPCodeList.addAll(codeSet);
		//卡名称和卡代码对应
		List<CardProdunctDefinition> cardProDefObj = cpdm.queryCardNameByCode(cardPCodeList);
		for(int m=0;m<cardProDefObj.size();m++){
			CardProdunctDefinition cardDef = cardProDefObj.get(m);
			cardCodeAndCardNameMap.put(cardDef.getCardpCode(), cardDef.getCardpName());
		}
		//查询卡片物理类型名称
		List<CardPhysicsType> cardPhysicTypeList = cptm.queryAllCardPhysicsType();
		for(int n=0;n<cardPhysicTypeList.size();n++){
			CardPhysicsType cardTypeObj = cardPhysicTypeList.get(n);
			cardTypeCodeAndNameMap.put(cardTypeObj.getCardTypeCode(), cardTypeObj.getCardTypeName());
		}
		
		//通过配送任务号，查询出库号
		String storageHistoryNo = sdm.queryStorageNoByDistributeTaskNo(distributeTaskNo,activeUser.getBranchNo());
		logger.debug("之前配送出库号===>"+storageHistoryNo);	
		
		//0 更新出入库记录
		srm.updateStorageNoByDistribute(storageHistoryNo);
		// 检索出来源网点
		StorageReg srObj = srm.queryStorageRegByStorNo(storageHistoryNo);
		String sourceBranchNo = srObj.getSourceBranchNo();
		logger.debug("sourceBranchNo==>"+sourceBranchNo);
		//1 生成出入库记录
		String storageNo = inventoryRecordNoUtil.getStorageNo();
		logger.debug("新的出入库号==>"+storageNo);
		StorageReg sr=new StorageReg();
		sr.setStorageNo(storageNo);
		sr.setBussinessNo("");
		sr.setStorageDetailNo("");
		sr.setAmount(citizenNoList.size());
		sr.setStorageMode(storageModeByTurnIn);
		sr.setStorageType("0");
		if("04".equals(storageModeByTurnIn)){
			sr.setStorageReason("中心库接收空白卡上缴");
		}else if("03".equals(storageModeByTurnIn)){
			sr.setStorageReason("中心库接收废卡上缴");
		}
		
		sr.setStorageDate(DateAndStampUtil.getCurrentDate());
		sr.setRevocationDate("");
		sr.setRevocationOperatorNo("");
		sr.setRevocationBranchNo("");
		sr.setStartNo("");
		sr.setEndNo("");
		sr.setStorageStatus("1");
		sr.setSourcePosition("2");
		sr.setDesPosition("1");
		//这边先写死，来源网点,中心库
		sr.setSourceBranchNo(sourceBranchNo);
		sr.setDesBranchNo(activeUser.getBranchNo());
		sr.setIsReceive("");
		sr.setBothSeqNo("");
		sr.setDataInMode("0");
		sr.setOperatorNo(activeUser.getUserNo().toString());
		sr.setOperateBranchNo(activeUser.getBranchNo());
		sr.setInputDate(DateAndStampUtil.getCurrentDate());
		sr.setRemark("");
		sr.setRevocationBussinessNo("");
		logger.debug("sr==>"+sr.toString());
		//插入出入库登记表
		srm.insert(sr);
		
		
		//2 生成出入库明细
		StorageDetail sd=new StorageDetail();
		String detailNo = getDetailNo();
		sd.setStorageDetailNo(detailNo);
		sd.setStorageNo(storageNo);
		sd.setAmount(citizenNoList.size());
		sd.setDistributeTaskNo(distributeTaskNo);
		logger.debug("sd==>"+sd.toString());
		sdm.insert(sd);//更新出入库明细表
		
		//3 生成库存汇总
		String ID = stockdm.queryMaxDetailId();
		if("".equals(ID)||null==ID){
				ID = "1";
		}
		int id = Integer.parseInt(ID)+1;
		Set<Map.Entry<String,Integer>> entrySet = cardCodeAndTypeAmountMap.entrySet();
		for(Map.Entry<String,Integer> entry:entrySet){
			StockSum ss = new StockSum();
			String key = entry.getKey();
			String[] codeAndPTypeArray = key.split("#");
			String cardPCode = codeAndPTypeArray[0];
			String phsicType = codeAndPTypeArray[1];
			String stockType = codeAndPTypeArray[2];
			amountList.add(entry.getValue());
			cardPNameList.add(cardCodeAndCardNameMap.get(cardPCode)+cardTypeCodeAndNameMap.get(phsicType));
			ss.setBranchNo(activeUser.getBranchNo());
			ss.setCardpCode(cardPCode);
			ss.setStockPosition("1");
			ss.setCardPhysicType(phsicType);
			ss.setCardStockType(stockType);
			ss.setCardpName(cardCodeAndCardNameMap.get(cardPCode));
			
			//现根据卡产品代码，网点编号，stockStatus=1条件查询库中是否有数据，
			//如果没有则插入一条数据，然后再更新
			//如果有，则直接更新
			
			String stockSumID = ssm.queryStockSumNoByCardPCode(ss);
			logger.debug("库存汇总ID==>"+stockSumID);
			String stockSumIDToUpdate = null;
			if("".equals(stockSumID) || stockSumID==null){
				//查找库存汇总表中最大的ID号
				String newID = null;
				String maxStockSumID = ssm.queryMaxStockSumID();
				Integer no = Integer.parseInt(maxStockSumID.substring(4))+1;
				//取得的数字的长度
				int numLength = String.valueOf(no).length();
				//判断取得的数字长度与字段长度，如果小于字段长度，那么说明字段的数字位是以0开头的，需要补位
				int addZero = maxStockSumID.substring(4).length()-numLength;
				if(addZero>0){
					int len = maxStockSumID.substring(4).length();
					newID = "KCHZ"+String.format("%0" + len + "d", no);
				}
				if(addZero==0){
					newID = "KCHZ"+no;
				}
				logger.debug("库存出入库汇总号是==>"+newID);
				ss.setStockSumId(newID);
				ss.setTotalNum(0);
				ss.setCurrNum(0);
				ss.setRealOutNum(0);
				ss.setOutSum(0);
				ssm.insertNewStockInfo(ss);
				stockSumIDToUpdate = newID;
			}else{
				stockSumIDToUpdate = stockSumID;
			}
			//更新前，锁死要更新的行
			StockSum stockSumObjTemp = ssm.queryStockSumBySumId(stockSumIDToUpdate);
			ss.setLastOperator(activeUser.getUserNo().toString());
			ss.setLastModDate(DateAndStampUtil.getCurrentDate());
			ss.setOperatorAmount(entry.getValue());
			
			logger.debug("ss==>"+ss.toString());
			ssm.updateStockSumByIcoming(ss);
			
			StockDetail stockDetail = new StockDetail();
			stockDetail.setStockSumId(stockSumIDToUpdate);
			stockDetail.setStockDetailId(id);
			stockDetail.setTaskNo(distributeTaskNo);
		//制卡返回文件号，这里不需要，可以从入库出库明细中查询
		//	stockDetail.setMakecardReturnNo(makeCardNoList.get(i));
			stockDetail.setItemAttrVal03("");
			stockDetail.setItemAttrVal04("");
			stockDetail.setItemAttrVal05("");
			stockDetail.setAmount(entry.getValue());
			stockDetail.setInStockStat("0");
			stockDetail.setLstInNo(storageNo);
			stockDetail.setLstOutNo("");
			stockDetail.setLstInDate(DateAndStampUtil.getCurrentDate());
			stockDetail.setLstOutDate("");
			stockDetail.setLstInOperator(activeUser.getUserNo().toString());
			stockDetail.setLstOutOperator("");
			stockDetail.setFileDate("");
			stockDetail.setFileFlag("");
			logger.debug("stockDetail===>"+stockDetail.toString());
			stockdm.insert(stockDetail);
			id++;
		}
		
		Date currentDate = new Date();
		String empNo = String.valueOf(activeUser.getUserNo());
		//5.插入卡管理表
		List<CardManage> cardMagList = new ArrayList<CardManage>();
		List<CardControl> cardControlObjList = new ArrayList<CardControl>();
		for(int i=0;i<citizenNoList.size();i++){
			CardManage cme = new CardManage();
			String currProcId = UUID.randomUUID().toString().replace("-", "");
			cme.setProcessId(currProcId);
			cme.setApplyBranchNo(activeUser.getBranchNo());
			cme.setApplyDate(new Date());
			cme.setApplyTellerNo(empNo);
			cme.setBusinessNo("");
			cme.setProcessCode(CardContants.CARD_PROC_HANDEDREV);
			cme.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_HANDEDREV));
			cme.setCitizenCardNo(citizenNoList.get(i));
			cme.setCardPosition(CardContants.CARD_POSITION_CENTRAL_STOREROOM);
		//	cme.setCardStatus(CardContants.CARD_STATE_DISABLED);
		//	cme.setApplyWay("");// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
			cardMagList.add(cme);
			
			CardControl cardControlObj = cardControlMap.queryCardControlByCitizenCardNo(citizenNoList.get(i));
			cardControlObj.setCardPosition("1");
			cardControlObj.setCurrProcId(currProcId);
			cardControlObj.setLastDate(currentDate);
			cardControlObj.setLastOperator(empNo);
			cardControlObjList.add(cardControlObj);
		}
		cmm.batchInsert(cardMagList);
		
		//6 更新卡控制表		
		cardControlMap.updateControlByDistribution(cardControlObjList);
		
		//入库号
		resultMap.put("storageNo", storageNo);
		//网点号
		resultMap.put("branchNo", activeUser.getBranchNo());
		//入库总数量(因为这里是只选择一项，数量暂时这么编辑，后期需要改正)
		resultMap.put("totalAmount", String.valueOf(citizenNoList.size()));
		//入库日期
		resultMap.put("curDate", DateAndStampUtil.getCurrentDate());
		//清单明细抬头
		if("04".equals(storageModeByTurnIn)){
			resultMap.put("title", "中心库接收空白卡/成品卡上缴入库清单");
		}else if("03".equals(storageModeByTurnIn)){
			resultMap.put("title", "中心库接收废卡/注销卡上缴入库清单");
		}
		
		//卡产品名称列表
		
		resultMap.put("cardPNameList", cardPNameList);
		//制卡批号列表
	//	resultMap.put("makeCardNoList", applyBatchNoList);
		//制卡商名称列表
		resultMap.put("companyList", "");
		//每个批号的数量列表
		resultMap.put("amountList", amountList);
		//凭证类型
		resultMap.put("credential_type", "storage");
		
		//预览清单
		createStoragePDF(resultMap);
		
		//移动任务文件
//		String sourcePath = "D:\\Apache24\\htdocs\\qzsmk\\resource\\blankAndRejectTaskFile\\"+distributeTaskNo+".txt";
		String sourcePath = BLANK_REJECT_TASK_PATH +File.separator+distributeTaskNo+".txt";
//		String fileReceivedPath = "D:\\Apache24\\htdocs\\qzsmk\\resource\\blankAndRejectTaskFileReceived";
		String fileReceivedPath = BLANK_REJECT_TASK_RECEIVED_PATH;
		logger.debug("sourcePath==>"+sourcePath);
		//暂时不适用移动文件的方法，先使用根据配送任务号查出入库记录号是否被接受，如果被接收了，就不显示出来
		FileUtil.moveTotherFolders(sourcePath,fileReceivedPath);
		
		Map<String,Object> rMap = new HashMap<String,Object>();
		rMap.put("credential_type", "storage");
		rMap.put("title", resultMap.get("title"));
		rMap.put("ipAddress", IP_ADDRESS);
		rMap.put("storageNo", storageNo);
		
		return rMap;
	}

	@Override
	@SystemServiceLog(description = "废卡信息查询")
	public DwzPage<Map<String, String>> getRejectCardReceiving(Map<String, String> map, Integer pageNum,
			Integer numPerPage) {
		String distributeTaskNo = map.get("distributeTaskNo");
		logger.debug("废卡配送任务号===>"+distributeTaskNo);
		//读取指定目录下的文件信息 REJECT_DISTRIBUTSUCCESS_PATH
//		String filePath = "D:\\resource\\distributeSuccessTask\\"+distributeTaskNo+".txt";
		String filePath = BLANK_REJECT_TASK_PATH+File.separator+distributeTaskNo+".txt";
		//文件中每行内容列表
		List<Map<String,String>> lineList = new ArrayList<Map<String,String>>();
		
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");
		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		
		//查询该任务号对应的接收标志是否是0，0：未接收，1：已接收
		String receivingFlag = srm.queryStorageNoReceivingFlag(distributeTaskNo,activeUser.getBranchNo());
		if("0".equals(receivingFlag)||"".equals(receivingFlag)){
			File file = new File(filePath);
			FileInputStream fis = null;
			InputStreamReader isr = null;
			BufferedReader br = null;
			String line = null;
			try {
				fis = new FileInputStream(file);
				isr = new InputStreamReader(fis,"utf-8");
				br = new BufferedReader(isr);
				while((line=br.readLine())!=null){
					String[] itemArray = line.split("\\|");
					//市民卡号,卡产品代码的map
					Map<String,String> lineMap = new HashMap<String,String>();
					lineMap.put("citizenCardNo",itemArray[1]);
					lineMap.put("cardpCode",itemArray[2]);
					lineMap.put("cardType",itemArray[3]);
					lineMap.put("stockType",itemArray[4]);
					logger.debug("lineMap===>"+lineMap);
					lineList.add(lineMap);
				}
			} catch (Exception e) {

				e.printStackTrace();
			}finally{
				if(br!=null){
					try {
						br.close();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(isr!=null){
					try {
						isr.close();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(fis!=null){
					try {
						fis.close();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		
		List<Map<String,String>> returnList = new ArrayList<Map<String,String>>();
		
		Integer startLine = (pageNum-1)*numPerPage;
		logger.debug("startLine==>"+startLine);
		if(lineList.size()>=2){
			if(lineList.size()-1<=numPerPage){
				returnList = lineList.subList(1, lineList.size());
			}else{
				if((lineList.size()-1-startLine)>numPerPage){
					returnList = lineList.subList(startLine+1, startLine+1+numPerPage);
				}else{
					returnList = lineList.subList(startLine+1, lineList.size());
				}	
			}
		}
		logger.debug("returnList.size()==>"+returnList.size());
		
		
		//分页处理
		DwzPage<Map<String,String>> dp = new DwzPage<Map<String,String>>(pageNum, numPerPage ,lineList.size()-1);
		dp.setList(returnList);
		logger.debug("配送信息==>"+returnList);
		return dp;
	}

	@Override
	@SystemServiceLog(description = "废卡入库")
	@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
	public Map<String, Object> RejectCardReceivingRegist(String[] checkedeParam) throws InventoryException {
		//卡产品代码列表集合
		List<String> cardPCodeList = new ArrayList<String>();
		
		List<String> cardControlIdList = new ArrayList<String>();
		//卡产品对应的数量，组成的map对象
		Map<String,Integer> cardCodeAndAmountMap = new HashMap<String,Integer>();
		//卡产品名称列表集合
		List<String> cardPNameList = new ArrayList<String>();
		//卡产品对应的数量列表集合
		List<String> amountList = new ArrayList<String>();
		//返回的打印用参数map
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String distributeTaskNo = null;
		String sourceBranchNo = null;
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");
		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		//解析传递过来的参数
		for(int i=0;i<checkedeParam.length;i++){
			Integer amount = 1;
			String[] itemArray = checkedeParam[i].split("#");
			distributeTaskNo = itemArray[0];
			String citizenCardNo = itemArray[1];
			String cardpName = itemArray[2];
			String cardpCode = itemArray[3];
			String controlId = itemArray[4];
			logger.debug("citizenCardNo===>"+citizenCardNo);
			logger.debug("cardpName===>"+cardpName);
			logger.debug("distributeTaskNo===>"+distributeTaskNo);
			logger.debug("cardpCode===>"+cardpCode);
			logger.debug("controlId===>"+controlId);
			if(cardCodeAndAmountMap.containsKey(cardpCode)){
				amount = cardCodeAndAmountMap.get(cardpCode) + 1;				
			}else{
				amount = 1;
				cardPNameList.add(cardpName);
				cardPCodeList.add(cardpCode);
			}
			cardCodeAndAmountMap.put(cardpCode, amount);
			cardControlIdList.add(controlId);
		}
		sourceBranchNo = distributeTaskNo.substring(0, 8);
		logger.debug("sourceBranchNo==>"+sourceBranchNo);
		logger.debug("cardCodeAndAmountMap===>"+cardCodeAndAmountMap);
		
		
		for(int n=0;n<cardPCodeList.size();n++){
			String cardPCode = cardPCodeList.get(n);
			String amount = String.valueOf(cardCodeAndAmountMap.get(cardPCode));
			amountList.add(amount);
		}
		
		//通过配送任务号，查询出库号
		String storageHistoryNo = sdm.queryStorageNoByDistributeTaskNo(distributeTaskNo,activeUser.getBranchNo());
		logger.debug("之前配送出库号===>"+storageHistoryNo);	
		
		//0 更新出入库记录(这边忘了更新工作人编号和日期)
		// 0.1更新前，先确认是否已接收，已经接收，那就抛出异常
		String isReceiveFlag = srm.queryIsReceiveByStorageNo(storageHistoryNo);
		if("1".equals(isReceiveFlag)){
			throw new InventoryException("信息有误,请返回刷新页面后重新操作！");
		}
		srm.updateStorageNoByDistribute(storageHistoryNo);
		
		//1 生成出入库记录
		String storageNo = inventoryRecordNoUtil.getStorageNo();
		logger.debug("新的出入库号==>"+storageNo);
		StorageReg sr=new StorageReg();
		sr.setStorageNo(storageNo);
		sr.setBussinessNo("");
		sr.setStorageDetailNo("");
		sr.setAmount(checkedeParam.length);
		sr.setStorageMode("03");
		sr.setStorageType("0");
		sr.setStorageReason("中心接收废卡上缴");
		sr.setStorageDate(DateAndStampUtil.getCurrentDate());
		sr.setRevocationDate("");
		sr.setRevocationOperatorNo("");
		sr.setRevocationBranchNo("");
		sr.setStartNo("");
		sr.setEndNo("");
		sr.setStorageStatus("1");
		sr.setSourcePosition("2");
		sr.setDesPosition("0");
		//这边先写死，来源网点,中心库
		sr.setSourceBranchNo(sourceBranchNo);
		sr.setDesBranchNo(activeUser.getBranchNo());
		sr.setIsReceive("");
		sr.setBothSeqNo("");
		sr.setDataInMode("0");
		sr.setOperatorNo(activeUser.getUserNo().toString());
		sr.setOperateBranchNo(activeUser.getBranchNo());
		sr.setInputDate(DateAndStampUtil.getCurrentDate());
		sr.setRemark("");
		sr.setRevocationBussinessNo("");
		logger.debug("sr==>"+sr.toString());
		//插入出入库登记表
		srm.insert(sr);
		
		//2 生成出入库明细
		StorageDetail sd=new StorageDetail();
		String detailNo = getDetailNo();
		sd.setStorageDetailNo(detailNo);
		sd.setStorageNo(storageNo);
		sd.setAmount(checkedeParam.length);
		sd.setDistributeTaskNo(distributeTaskNo);
		logger.debug("sd==>"+sd.toString());
		sdm.insert(sd);//更新出入库明细表
		
		//3 生成库存汇总
		String ID = stockdm.queryMaxDetailId();
		if("".equals(ID)||null==ID){
				ID = "1";
		}
		int id = Integer.parseInt(ID)+1;
		for(int k=0;k<cardPCodeList.size();k++){
			StockSum ss = new StockSum();
			String cardPCode = cardPCodeList.get(k);
			ss.setBranchNo(activeUser.getBranchNo());
			ss.setCardpCode(cardPCode);
			ss.setStockPosition("1");
			ss.setCardpName(cardPNameList.get(k));
			
			//现根据卡产品代码，网点编号，stockStatus=1条件查询库中是否有数据，
			//如果没有则插入一条数据，然后再更新
			//如果有，则直接更新
			
			String stockSumID = ssm.queryStockSumNoByCardPCode(ss);
			logger.debug("库存汇总ID==>"+stockSumID);
			String stockSumIDToUpdate = null;
			if("".equals(stockSumID) || stockSumID==null){
				//查找库存汇总表中最大的ID号
				String newID = null;
				String maxStockSumID = ssm.queryMaxStockSumID();
				Integer no = Integer.parseInt(maxStockSumID.substring(4))+1;
				//取得的数字的长度
				int numLength = String.valueOf(no).length();
				//判断取得的数字长度与字段长度，如果小于字段长度，那么说明字段的数字位是以0开头的，需要补位
				int addZero = maxStockSumID.substring(4).length()-numLength;
				if(addZero>0){
					int len = maxStockSumID.substring(4).length();
					newID = "KCHZ"+String.format("%0" + len + "d", no);
				}
				if(addZero==0){
					newID = "KCHZ"+no;
				}
				logger.debug("库存出入库汇总号是==>"+newID);
				ss.setStockSumId(newID);
				ss.setTotalNum(0);
				ss.setCurrNum(0);
				ss.setRealOutNum(0);
				ss.setOutSum(0);
				ssm.insertNewStockInfo(ss);
				stockSumIDToUpdate = newID;
			}else{
				stockSumIDToUpdate = stockSumID;
			}
			
			//更新前，锁死要更新的行
			StockSum stockSumObjTemp = ssm.queryStockSumBySumId(stockSumIDToUpdate);
			ss.setLastOperator(activeUser.getUserNo().toString());
			ss.setLastModDate(DateAndStampUtil.getCurrentDate());
			ss.setOperatorAmount(cardCodeAndAmountMap.get(cardPCode));
			
			logger.debug("ss==>"+ss.toString());
			ssm.updateStockSumByIcoming(ss);

			
			
			StockDetail stockDetail = new StockDetail();
			stockDetail.setStockSumId(stockSumIDToUpdate);
			stockDetail.setStockDetailId(id);
			stockDetail.setTaskNo(distributeTaskNo);
		//制卡返回文件号，这里不需要，可以从入库出库明细中查询
		//	stockDetail.setMakecardReturnNo(makeCardNoList.get(i));
			stockDetail.setItemAttrVal03("");
			stockDetail.setItemAttrVal04("");
			stockDetail.setItemAttrVal05("");
			stockDetail.setAmount(cardCodeAndAmountMap.get(cardPCode));
			stockDetail.setInStockStat("0");
			stockDetail.setLstInNo(storageNo);
			stockDetail.setLstOutNo("");
			stockDetail.setLstInDate(DateAndStampUtil.getCurrentDate());
			stockDetail.setLstOutDate("");
			stockDetail.setLstInOperator(activeUser.getUserNo().toString());
			stockDetail.setLstOutOperator("");
			stockDetail.setFileDate("");
			stockDetail.setFileFlag("");
			logger.debug("stockDetail===>"+stockDetail.toString());
			stockdm.insert(stockDetail);
			id++;
		}
		
		//5 更新卡控制表
		String position = "1";
		String empNo = String.valueOf(activeUser.getUserNo());
		//废卡是已发卡，不需要更新卡申领状态
	//	String claimStatus = "";
		Date lastDate = new Date();
		Date cardDate = null;
	//	cardControlMap.updateControlByDistribution(cardControlIdList, position, empNo, lastDate, cardDate);
		// 其余数据表操作 凭证表，业务表
		
		//移动任务文件
	//	String sourcePath = "D:\\resource\\distributeSuccessTask\\"+distributeTaskNo+".txt";
		String sourcePath = REJECT_DISTRIBUTSUCCESS_PATH+File.separator+distributeTaskNo+".txt";
	//	String fileReceivedPath = "D:\\Apache24\\htdocs\\qzsmk\\resource\\blankAndRejectTaskFileReceived";
		String fileReceivedPath = BLANK_REJECT_TASK_RECEIVED_PATH;
		logger.debug("sourcePath==>"+sourcePath);
		//暂时不适用移动文件的方法，先使用根据配送任务号查出入库记录号是否被接受，如果被接收了，就不显示出来
		FileUtil.moveTotherFolders(sourcePath,fileReceivedPath);
		
		//打印参数
		
		List<String> applyBatchNoList = new ArrayList<String>();
//		applyBatchNoList.add(distributeTaskNo);
		
		//入库号
		resultMap.put("storageNo", storageNo);
		//网点号
		resultMap.put("branchNo", activeUser.getBranchNo());
		//入库总数量(因为这里是只选择一项，数量暂时这么编辑，后期需要改正)
		resultMap.put("totalAmount", String.valueOf(checkedeParam.length));
		//入库日期
		resultMap.put("curDate", DateAndStampUtil.getCurrentDate());
		//清单明细抬头
		resultMap.put("title", "中心库接收废卡上缴入库清单");
		//卡产品名称列表
		
		resultMap.put("cardPNameList", cardPNameList);
		//制卡批号列表
		resultMap.put("makeCardNoList", applyBatchNoList);
		//制卡商名称列表
		resultMap.put("companyList", "");
		//每个批号的数量列表
		resultMap.put("amountList", amountList);
		//凭证类型
		resultMap.put("credential_type", "storage");
		return resultMap;
	}

	@Override
	@SystemServiceLog(description = "查询出入库清单列表")
	public Map<String, Object> getStorageList(Map<String, String> map) {
		String storageDateFrom = map.get("storageDateFrom");
		String storageDateTo = map.get("storageDateTo");
		String storageMode = map.get("storageMode");
		String storageBranchNo = map.get("storageBranchNo");
		logger.debug("storageDateFrom===>"+storageDateFrom);
		logger.debug("storageDateTo===>"+storageDateTo);
		logger.debug("storageMode===>"+storageMode);
		logger.debug("storageBranchNo===>"+storageBranchNo);
	//	logger.debug("numPerPage==>"+numPerPage);
	//	logger.debug("currentPage==>"+currentPage);
	//	Integer startLine = (currentPage-1)*numPerPage;
		List<StorageRegVo> storageRegList = srm.queryStorageSumList(storageDateFrom,storageDateTo,storageMode,storageBranchNo);
		//鱼洲杰修改
		Integer totalCount =srm.queryStorageSumListNumber(storageDateFrom, storageDateTo, storageMode, storageBranchNo);
	//	DwzPage<StorageRegVo> dp = new DwzPage<StorageRegVo>(currentPage, numPerPage ,totalCount);
	//	dp.setList(storageRegList);
		
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("list", storageRegList);
		resultMap.put("ipAddress", IP_ADDRESS);
		return resultMap;
	}

	@Override
	@SystemServiceLog(description = "查询可以领用的卡片信息")
	public DwzPage<CardTask> getCardInfoByEmpReceive(Map<String, String> map, Integer currentPage,
			Integer numPerPage) {
		List<CardTask> reveiveCardInfo = new ArrayList<CardTask>();
		logger.debug("map==>"+map);
		String receiveCardClassify = map.get("receiveCardClassify");
		Integer requestAmount = Integer.parseInt(map.get("requestAmount"));
		String taskNo = map.get("taskNo");
		String applyCompany = map.get("applyCompany");
		String branchNo = map.get("branchNo");
		if("1".equals(receiveCardClassify)){
			reveiveCardInfo = ctm.queryCardByBlankAppAndBatchApp(branchNo,requestAmount);
			
		}else if("2".equals(receiveCardClassify)){
			
		}
		
		DwzPage<CardTask> dp = new DwzPage<CardTask>(currentPage, numPerPage ,reveiveCardInfo.size());
		ListPageUtil<CardTask> listPageUtil = new ListPageUtil<CardTask>(reveiveCardInfo,currentPage, numPerPage);
		List<CardTask> pagedList = listPageUtil.getPagedList();
		dp.setList(pagedList);
		logger.debug("页面表格信息==>"+pagedList);
		return dp;
	}

	@Override
	public List<StorageModeDefinition> queryStorageModeDefinition(String storageModeType) {
		List<StorageModeDefinition> storageDefinitionList = null;
		storageDefinitionList = smdm.queryStorageModeDef(storageModeType);
		return storageDefinitionList;
	}
	
	/**
	 * 
	 */
	@Override
	@SystemServiceLog(description = "请求卡产品类型，和对应的网点的卡产品库存数量")
	public Map<String, Object> queryCardAmountInfo(String cardClassifyDef, String empNo, String empBranch) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//根据下拉框的选择，判断卡类型值
		//查询出所有的卡产品定义,查询出卡产品对应网点的库存数量
		List<CardStockQuantityVo> cardStockQuantityObj = csqm.queryCardStockQuantity(cardClassifyDef,empNo,empBranch);
		resultMap.put("cardStockQuantityObj", cardStockQuantityObj);
		logger.debug("cardStockQuantityObj==>"+cardStockQuantityObj);
		return resultMap;
	}

	@Override
	@SystemServiceLog(description = "柜员领用登记")
	@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
	public Map<String, Object> ReceiveCardByEmpRegister(HttpServletRequest request) {
		// 卡产品列表
		List<String> cardPCodeList = new ArrayList<String>();
		// 卡产品名称列表
		List<String> cardPNameList = new ArrayList<String>();
		//返回的打印用参数map
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//记录每个卡种的数量
		List<Integer> amountList = new ArrayList<Integer>();
		//记录卡片物理类型
		List<String> cardPhysicTypeList = new ArrayList<String>();
		//算出出库总数量
		Integer totalAmount = 0;
		String[] requiredQuantityArray = request.getParameterValues("receivedQuantity");
		String[] receiveCardPCodeArray = request.getParameterValues("receiveCardPCode");
		String[] receiveCardPNameArray = request.getParameterValues("receiveCardPName");
		String[] receivedCardPhysicTypeArray = request.getParameterValues("receiveCardPhysicType");
		String branchNo = request.getParameter("branchNoByEmpReceiveBlank");
		String operatorNo = request.getParameter("operatorNo");
		String empNoByReceiveBlank = request.getParameter("empReceiveBlank");
		for(int i=0;i<requiredQuantityArray.length;i++){
			Integer amount = 0;
			if(!"".equals(requiredQuantityArray[i])&&requiredQuantityArray[i]!=null){
				amount = Integer.parseInt(requiredQuantityArray[i]);
			}
			
			totalAmount+=amount;
			//编辑卡产品及对应的数量
			if(amount>0){
				cardPCodeList.add(receiveCardPCodeArray[i]);
				cardPNameList.add(receiveCardPNameArray[i]);
				cardPhysicTypeList.add(receivedCardPhysicTypeArray[i]);
				amountList.add(amount);
			}
		}
		logger.debug("totalAmount==>"+totalAmount);
		//出入库登记
		String storageNo = inventoryRecordNoUtil.getStorageNo();
		logger.debug("新的出入库号==>"+storageNo);
		StorageReg sr=new StorageReg();
		sr.setStorageNo(storageNo);
		sr.setBussinessNo("");
		sr.setStorageDetailNo("");
		sr.setAmount(totalAmount);
		//出库模式 15
		sr.setStorageMode("16");
		//出库为1
		sr.setStorageType("1");
		sr.setStorageReason("柜员领用出库");
		sr.setStorageDate(DateAndStampUtil.getCurrentDate());
		sr.setRevocationDate("");
		sr.setRevocationOperatorNo("");
		sr.setRevocationBranchNo("");
		sr.setStartNo("");
		sr.setEndNo("");
		sr.setStorageStatus("1");
		sr.setSourcePosition("2");
		sr.setDesPosition("2");
		//这边先写死，来源网点,中心库
		sr.setSourceBranchNo(branchNo);
		sr.setDesBranchNo(branchNo);
		sr.setIsReceive("");
		sr.setBothSeqNo("");
		sr.setDataInMode("0");
		sr.setOperatorNo(operatorNo);
		sr.setOperateBranchNo(branchNo);
		sr.setInputDate(DateAndStampUtil.getCurrentDate());
		sr.setRemark("");
		sr.setRevocationBussinessNo("");
		logger.debug("sr==>"+sr.toString());
		//插入出入库登记表
		srm.insert(sr);
		//出入库明细
		//2 生成出入库明细
		StorageDetail sd=new StorageDetail();
		String detailNo = getDetailNo();
		sd.setStorageDetailNo(detailNo);
		sd.setRequestUserNo(empNoByReceiveBlank);
		sd.setStorageNo(storageNo);
		sd.setAmount(totalAmount);
		logger.debug("sd==>"+sd.toString());
		sdm.insert(sd);
		
		
		
		
		//3 生成库存汇总
		String ID = stockdm.queryMaxDetailId();
		if("".equals(ID)||null==ID){
				ID = "1";
		}
		int id = Integer.parseInt(ID)+1;
		for(int k=0;k<cardPCodeList.size();k++){
			StockSum ss = new StockSum();
			String cardPCode = cardPCodeList.get(k);
			ss.setBranchNo(branchNo);
			ss.setCardpCode(cardPCode);
			ss.setStockPosition("2");
			ss.setCardStockType("1");
			ss.setCardpName(cardPNameList.get(k));
			ss.setCardPhysicType(cardPhysicTypeList.get(k));
			
			//现根据卡产品代码，网点编号，stockStatus=1条件查询库中是否有数据，
			//如果没有则插入一条数据，然后再更新
			//如果有，则直接更新
			
			String stockSumID = ssm.queryStockSumNoByCardPCode(ss);
			logger.debug("库存汇总ID==>"+stockSumID);
			
			//更新前，锁死要更新的行
			StockSum stockSumObjTemp = ssm.queryStockSumBySumId(stockSumID);
			ss.setLastOperator(operatorNo);
			ss.setLastModDate(DateAndStampUtil.getCurrentDate());
			ss.setOperatorAmount(amountList.get(k));
			
			logger.debug("ss==>"+ss.toString());
			//柜员领用也算出库，sql文可以和网点配送到中心库的sql文使用一个
			ssm.updateStockSumByDistributeToCenter(ss);

			
			
			StockDetail stockDetail = new StockDetail();
			stockDetail.setStockSumId(stockSumID);
			stockDetail.setStockDetailId(id);
			stockDetail.setTaskNo("");
		//制卡返回文件号，这里不需要，可以从入库出库明细中查询
		//	stockDetail.setMakecardReturnNo(makeCardNoList.get(i));
			stockDetail.setItemAttrVal03("");
			stockDetail.setItemAttrVal04("");
			stockDetail.setItemAttrVal05("");
			stockDetail.setAmount(amountList.get(k));
			stockDetail.setInStockStat("1");
			stockDetail.setLstInNo("");
			stockDetail.setLstOutNo(storageNo);
			stockDetail.setLstInDate("");
			stockDetail.setLstOutDate(DateAndStampUtil.getCurrentDate());
			stockDetail.setLstInOperator("");
			stockDetail.setLstOutOperator(operatorNo);
			stockDetail.setFileDate("");
			stockDetail.setFileFlag("");
			logger.debug("stockDetail===>"+stockDetail.toString());
			stockdm.insert(stockDetail);
			id++;
		}
		//更新卡状态
		//找出所有卡产品，对应的卡控制号（怎么记录领用卡片的人）
		//根据每个卡产品代码，网点，按卡号增序，请求数量，查找出控制号再更新控制ID对应的位置号
		
		//卡控制号List
		List<String> cardControlIDList = new ArrayList<String>();
		List<CardControl> cardControlLists = new ArrayList<CardControl>();
		for(int j=0;j<cardPCodeList.size();j++){
			String cardPCode = cardPCodeList.get(j);
			String cardPhysicType = cardPhysicTypeList.get(j);
			Integer amount = amountList.get(j);
			//SQL检索信息
			List<CardControl> cardControlList = cardControlMap.queryCardControlIDByEmp(cardPCode,cardPhysicType,amount,branchNo);
			cardControlLists.addAll(cardControlList);
		}
		//组装cardControlID
		for(int m=0;m<cardControlLists.size();m++){
			String cardControlId = String.valueOf(cardControlLists.get(m).getCardControlId());
			logger.debug("["+m+"]==>"+cardControlId);
			cardControlIDList.add(cardControlId);
		}
		
		//插入卡管理表
		//6.卡过程表
		List<CardData> cardDataObjList = cdm.queryCardDataByCardControlIdList(cardControlIDList);
		Date currentDate = new Date();
		List<CardManage> cardMagList = new ArrayList<CardManage>();
		List<CardControl> cardControlObjList = new ArrayList<CardControl>();
		for(int i=0;i<cardDataObjList.size();i++){
			CardManage cme = new CardManage();
			CardControl cardControlObj = new CardControl();
			String currProcId = UUID.randomUUID().toString().replace("-", "");
			cme.setProcessId(currProcId);
			cme.setApplyBranchNo(branchNo);
			cme.setApplyDate(new Date());
			cme.setApplyTellerNo(operatorNo);
			cme.setBusinessNo("");
			cme.setProcessCode(CardContants.CARD_PROC_REVBYEMP);
			cme.setProcessName("柜员领用");
			cme.setCitizenCardNo(cardDataObjList.get(i).getCitizenCardNo());
			cme.setCardPosition(CardContants.CARD_POSITION_COUNTER_EMPLOYEE);
			cme.setCardStatus(CardContants.CARD_STATE_DISABLED);
		//	cme.setApplyWay("");// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
			cardMagList.add(cme);
			
			cardControlObj.setLastDate(currentDate);
			cardControlObj.setLastOperator(operatorNo);
			cardControlObj.setCardPosition("3");
			cardControlObj.setCardPoaitionByEmp(empNoByReceiveBlank);
			cardControlObj.setCurrProcId(currProcId);
			cardControlObj.setCardControlId(cardDataObjList.get(i).getCardDataId());
			cardControlObjList.add(cardControlObj);
		}
		cmm.batchInsert(cardMagList);
		
		//更新控制ID,先进行行加锁
		List<String> cardPositionList = cardControlMap.queryCardPositionByControlId(cardControlIDList);
		cardControlMap.updateByReceivedEmp(cardControlObjList);
		
		
		
		//打印参数
		
		//出入库号
		resultMap.put("storageNo", storageNo);
		//网点号
		resultMap.put("branchNo", branchNo);
		//出入库总数量(因为这里是只选择一项，数量暂时这么编辑，后期需要改正)
		resultMap.put("totalAmount", String.valueOf(totalAmount));
		//出入库日期
		resultMap.put("curDate", DateAndStampUtil.getCurrentDate());
		//清单明细抬头
		resultMap.put("title", "柜员领用卡片清单");
		//卡产品名称列表
		
		resultMap.put("cardPNameList", cardPNameList);
		//制卡批号列表
		resultMap.put("makeCardNoList", "");
		//制卡商名称列表
		resultMap.put("companyList", "");
		//每个批号的数量列表
		resultMap.put("amountList", amountList);
		//凭证类型
		resultMap.put("credential_type", "storage");
		
		//预览清单
		createStoragePDF(resultMap);
		Map<String,Object> rMap = new HashMap<String,Object>();
		rMap.put("title", "柜员领用卡片清单");
		rMap.put("ipAddress", IP_ADDRESS);
		rMap.put("storageNo", storageNo);
		rMap.put("credential_type", "storage");
		return rMap;
	}
	
	@Override
	@SystemServiceLog(description = "检索在库的批次信息")
	@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
	public List<ApplyBatchInfo> queryBatchApplyRecordsByEmpReceive(HttpServletRequest request) {
		ApplyBatchInfo applyBatchInfoObj = new ApplyBatchInfo();
		applyBatchInfoObj.setBranchNo(request.getParameter("branchNoByEmpBatchReceived"));
		applyBatchInfoObj.setCardPName(request.getParameter("cardCodeByEmpReceiveCard"));
		applyBatchInfoObj.setCardType(request.getParameter("cardTypeByEmpReceiveCard"));
		applyBatchInfoObj.setCorpName(request.getParameter("corpNameByEmpReceived"));
		applyBatchInfoObj.setStartDate(request.getParameter("applyDateStartByEmpReceived"));
		applyBatchInfoObj.setEndDate(request.getParameter("applyDateEndByEmpReceived")); 
		
		
		List<ApplyBatchInfo> applyBatchInfoList = abim.queryApplyBatchInfoByEmpReceive(applyBatchInfoObj);
		
		return applyBatchInfoList;
	}

	@Override
	@SystemServiceLog(description = "初始化加载在库的批次信息")
	public Map<String, Object> getTaskInfoByEmpReceive() {
		Map<String,Object> obj = new HashMap<String,Object>();
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");
		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		ApplyBatchInfo applyBatchInfoObj = new ApplyBatchInfo();
		applyBatchInfoObj.setBranchNo(activeUser.getBranchNo());
		
		List<ApplyBatchInfo> applyBatchInfoList = abim.queryApplyBatchInfoByEmpReceive(applyBatchInfoObj);
		obj.put("applyBatchInfo", applyBatchInfoList);
		obj.put("branchNo", activeUser.getBranchNo());
		obj.put("empNo", activeUser.getUserNo());
		return obj;
	}

	@Override
	public Map<String, Object> batchInfoByEmpRegister(String[] checkedItem,String receiveEmpNo) {
		
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");
		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		
		Map<String, Object> resultMap = new HashMap<String,Object>();
		
		//任务列表
		List<String> taskNoList = new ArrayList<String>();
		//任务对应的数量
		Map<String,String> taskAndAmount = new HashMap<String,String>();
		//任务对应的卡产品
		Map<String,Integer> cardPCodeAndAmount = new HashMap<String,Integer>();
		//总数量
		Integer totalAmount = 0;
		//卡产品代码列表
		List<String> cardPCodeList = new ArrayList<String>();
		//卡产品名称列表
		List<String> cardPNameList = new ArrayList<String>();
		//数量列表
		List<String> amountList = new ArrayList<String>();
		//物理类型列表
		List<String> physicTypeList = new ArrayList<String>();
		//卡产品代码的卡产品名称
		Map<String,String> cardPCodeAndName = new HashMap<String,String>();
		String receivedEmpNo = receiveEmpNo ; 
		logger.debug("receivedEmpNo==>"+receivedEmpNo);
		String[] checkedItems = checkedItem;
		for(int i=0;i<checkedItems.length;i++){
			String[] checkedInfos = checkedItems[i].split("#");
			String taskNo = checkedInfos[0];
			String amount = checkedInfos[1];
			String cardPName = checkedInfos[2];
			String cardPCode = checkedInfos[3];
			String physicType = checkedInfos[checkedInfos.length-1].substring(3, 4);
			String cardPCodeAndPhysicType = cardPCode+"#"+physicType;
			totalAmount = totalAmount + Integer.parseInt(amount);
			taskNoList.add(taskNo);
			amountList.add(amount);
			physicTypeList.add(physicType);
			taskAndAmount.put(taskNo, amount);
			if(cardPCodeAndAmount.containsKey(cardPCodeAndPhysicType)){
				amount = cardPCodeAndAmount.get(cardPCodeAndPhysicType)+"#"+amount;
			}
			cardPCodeAndName.put(cardPCode, cardPName);
			cardPCodeAndAmount.put(cardPCodeAndPhysicType, Integer.parseInt(amount));
		}
		logger.debug("taskAndAmount==>"+taskAndAmount);
		logger.debug("cardPNameAndTaskNo==>"+cardPCodeAndAmount);
		String branchNo = activeUser.getBranchNo();
		String opeNo = String.valueOf(activeUser.getUserNo());
		//出库记录
		//出入库登记
		String storageNo = inventoryRecordNoUtil.getStorageNo();
		logger.debug("新的出入库号==>"+storageNo);
		StorageReg sr=new StorageReg();
		sr.setStorageNo(storageNo);
		sr.setBussinessNo("");
		sr.setStorageDetailNo("");
		sr.setAmount(totalAmount);
		//出库模式 15
		sr.setStorageMode("16");
		//出库为1
		sr.setStorageType("1");
		sr.setStorageReason("柜员领用出库");
		sr.setStorageDate(DateAndStampUtil.getCurrentDate());
		sr.setRevocationDate("");
		sr.setRevocationOperatorNo("");
		sr.setRevocationBranchNo("");
		sr.setStartNo("");
		sr.setEndNo("");
		sr.setStorageStatus("1");
		sr.setSourcePosition("2");
		sr.setDesPosition("2");
		//这边先写死，来源网点,中心库
		sr.setSourceBranchNo(branchNo);
		sr.setDesBranchNo(branchNo);
		sr.setIsReceive("");
		sr.setBothSeqNo("");
		sr.setDataInMode("0");
		sr.setOperatorNo(opeNo);
		sr.setOperateBranchNo(branchNo);
		sr.setInputDate(DateAndStampUtil.getCurrentDate());
		sr.setRemark("");
		sr.setRevocationBussinessNo("");
		logger.debug("sr==>"+sr.toString());
		//插入出入库登记表
		srm.insert(sr);
		
		//出库明细
		String detailNo = getDetailNo();
		for(int i=0;i<taskNoList.size();i++){
			StorageDetail sd=new StorageDetail();
			
			sd.setStorageDetailNo(detailNo);
			sd.setStorageNo(storageNo);
			sd.setAmount(Integer.parseInt(taskAndAmount.get(taskNoList.get(i))));
			sd.setTaskNo(taskNoList.get(i));
			logger.debug("sd["+i+"]==>"+sd);
			sdm.insert(sd);//更新出入库明细表
			
			//重新计算入库明细号，并追加1
			detailNo = getDetailNoNew(detailNo);
			logger.debug("detailNo==>"+detailNo);
		}
		
		
		//库存汇总明细
		//库存汇总
		String ID = stockdm.queryMaxDetailId();
		if("".equals(ID)||null==ID){
				ID = "1";
		}
		int id = Integer.parseInt(ID)+1;
		Set<Map.Entry<String,Integer>> entrySet = cardPCodeAndAmount.entrySet();
		for(Map.Entry<String,Integer> entry:entrySet){
			StockSum ss = new StockSum();
			String cardPCodeAndType = entry.getKey();
			String cardPCode = cardPCodeAndType.split("#")[0];
			String physicType = cardPCodeAndType.split("#")[1];
			ss.setBranchNo(branchNo);
			ss.setCardpCode(cardPCode);
			ss.setStockPosition("2");
			ss.setCardpName(cardPCodeAndName.get(cardPCode));
			ss.setCardStockType("2");
			ss.setCardPhysicType(physicType);
			
			String stockSumID = ssm.queryStockSumNoByCardPCode(ss);
			logger.debug("库存汇总ID==>"+stockSumID);	
			//更新前，锁死要更新的行
			StockSum stockSumObjTemp = ssm.queryStockSumBySumId(stockSumID);
			ss.setLastOperator(opeNo);
			ss.setLastModDate(DateAndStampUtil.getCurrentDate());
			ss.setOperatorAmount(entry.getValue());
			
			logger.debug("ss==>"+ss.toString());
			//柜员领用也算出库，sql文可以和网点配送到中心库的sql文使用一个
			ssm.updateStockSumByDistributeToCenter(ss);

			
			
			StockDetail stockDetail = new StockDetail();
			stockDetail.setStockSumId(stockSumID);
			stockDetail.setStockDetailId(id);
			stockDetail.setTaskNo("");
		//制卡返回文件号，这里不需要，可以从入库出库明细中查询
		//	stockDetail.setMakecardReturnNo(makeCardNoList.get(i));
			stockDetail.setItemAttrVal03("");
			stockDetail.setItemAttrVal04("");
			stockDetail.setItemAttrVal05("");
			stockDetail.setAmount(entry.getValue());
			stockDetail.setInStockStat("1");
			stockDetail.setLstInNo("");
			stockDetail.setLstOutNo(storageNo);
			stockDetail.setLstInDate("");
			stockDetail.setLstOutDate(DateAndStampUtil.getCurrentDate());
			stockDetail.setLstInOperator("");
			stockDetail.setLstOutOperator(opeNo);
			stockDetail.setFileDate("");
			stockDetail.setFileFlag("");
			logger.debug("stockDetail===>"+stockDetail.toString());
			stockdm.insert(stockDetail);
			id++;
		}
		
		//插入卡管理表
		//卡控制表状态,更新卡状态 
		List<String> cardControlIDList = cardControlMap.queryCardControlIDListByTaskNoList(taskNoList);
		List<CardData> cardDataObjList = cdm.queryCardDataByCardControlIdList(cardControlIDList);
		//卡过程表
		//查询出卡号
		Date currentDate = new Date();
		List<CardManage> cardMagList = new ArrayList<CardManage>();
		List<CardControl> cardControlObjList = new ArrayList<CardControl>();
		for(int i=0;i<cardDataObjList.size();i++){
			CardManage cme = new CardManage();
			
			String currProcId = UUID.randomUUID().toString().replace("-", "");
			cme.setProcessId(currProcId);
			cme.setApplyBranchNo(branchNo);
			cme.setApplyDate(new Date());
			cme.setApplyTellerNo(opeNo);
			cme.setBusinessNo("");
			cme.setProcessCode(CardContants.CARD_PROC_REVBYEMP);
			cme.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_REVBYEMP));
			cme.setCitizenCardNo(cardDataObjList.get(i).getCitizenCardNo());
			cme.setCardPosition(CardContants.CARD_POSITION_COUNTER_EMPLOYEE);
		//	cme.setCardStatus(CardContants.CARD_STATE_DISABLED);
		//	cme.setApplyWay("");// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
			cardMagList.add(cme);
			
			CardControl cardControlObj = cardControlMap.queryCardControlByCitizenCardNo(cardDataObjList.get(i).getCitizenCardNo());
			cardControlObj.setCurrProcId(currProcId);
			cardControlObj.setCardPosition(CardContants.CARD_POSITION_COUNTER_EMPLOYEE);
			cardControlObj.setCardPoaitionByEmp(receiveEmpNo);
			cardControlObj.setLastDate(currentDate);
			cardControlObj.setLastOperator(opeNo);
			cardControlObjList.add(cardControlObj);
			
		}
		cmm.batchInsert(cardMagList);
		
		
		//更新控制ID,先进行行加锁
		List<String> cardPositionList = cardControlMap.queryCardPositionByControlId(cardControlIDList);
		//20181214修改
		cardControlMap.updateByReceivedEmp(cardControlObjList);
		
		
		//打印参数
		//出入库号
		resultMap.put("storageNo", storageNo);
		//网点号
		resultMap.put("branchNo", branchNo);
		//出入库总数量(因为这里是只选择一项，数量暂时这么编辑，后期需要改正)
		resultMap.put("totalAmount", String.valueOf(totalAmount));
		//出入库日期
		resultMap.put("curDate", DateAndStampUtil.getCurrentDate());
		//清单明细抬头
		resultMap.put("title", "柜员领用卡片清单");
		//卡产品名称列表
		
		resultMap.put("cardPNameList", cardPNameList);
		//制卡批号列表
		resultMap.put("makeCardNoList", "");
		//制卡商名称列表
		resultMap.put("companyList", "");
		//每个批号的数量列表
		resultMap.put("amountList", amountList);
		//凭证类型
		resultMap.put("credential_type", "storage");
		
		//生成预览清单
		createStoragePDF(resultMap);
		
		Map<String,Object> rMap = new HashMap<String,Object>();
		rMap.put("ipAddress", IP_ADDRESS);
		rMap.put("storageNo", storageNo);
		rMap.put("credential_type", "storage");
		rMap.put("title", "柜员领用卡片清单");
		
		return rMap;
	}

	@Override
	public Map<String, List<ApplyBatchInfo>> queryBlankCardAmountInfo(String branchNo) {
		ApplyBatchInfo applyBatchInfoObj = new ApplyBatchInfo();
		applyBatchInfoObj.setBranchNo(branchNo);
		
		List<ApplyBatchInfo> obj = abim.queryBlankCardByEmpReceive(applyBatchInfoObj);
		
		for(int i=0;i<obj.size();i++){
			logger.debug("obj==>"+obj.get(i));
		}
		Map<String,List<ApplyBatchInfo>> map = new HashMap<String,List<ApplyBatchInfo>>();
		map.put("blankCardInfoList", obj);
		return map;
	}

	@Override
	public Map<String, Object> getReturnCardInfo(HttpServletRequest request) {
		Map<String,Object> returnCardInfoMap = new HashMap<String,Object>();
		returnCardInfoMap.put("cardPCode", request.getParameter("cardCodeByReturnCardByEmp"));
		returnCardInfoMap.put("cardType", request.getParameter("cardTypeByReturnCardByEmp"));
		returnCardInfoMap.put("citizenNo", request.getParameter("returnCardNo"));
		returnCardInfoMap.put("remark", request.getParameter("remarkByReturnCard"));
		logger.debug("returnCardInfoMap==>"+returnCardInfoMap);
		return returnCardInfoMap;
	}

	@Override
	public Map<String, Object> saveReturnCardRecords(HttpServletRequest request) {
		
		String[] cardPCodeArray = request.getParameterValues("cardCodeByEmpReturn");
		String[] cardTypeArray = request.getParameterValues("cardTypeByEmpReturn");
		String[] stockTypeArray = request.getParameterValues("stockTypeByEmpReturn");
		String[] citizenCardNoArray = request.getParameterValues("cardNoByEmpReturn");
		String branchNo = request.getParameter("branchNoByEmpReturn");
		String opeNo = request.getParameter("empNoByEmpReturn");
		//卡产品代码列表
		List<String> cardPCodeList = new ArrayList<String>();
		//市民卡号代码，数量列表
		List<String> citizenCardNoList = new ArrayList<String>();
		//卡物理类型
		List<String> physicTypeList = new ArrayList<String>();
		//卡片库存分类，成品，空白，废卡
		List<String> stockTypeList = new ArrayList<String>();
		//卡产品代码对应数量（卡产品代码，数量）
		Map<String,Integer> cardPCodeAndAmount = new HashMap<String,Integer>();
		//卡产品名称列表
		List<String> cardPNameList = new ArrayList<String>();
		//卡产品名称列表
		List<Integer> amountList = new ArrayList<Integer>();
		//卡控制ID列表
		List<String> cardControlIdList = new ArrayList<String>();
		//返回的打印用参数map
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		//市民卡与库存卡片种类的map
		Map<String,String> cardNoAndStocTypeMap = new HashMap<String,String>();
		
		//卡产品代码对应的卡产品名称map
		Map<String,String> cardCodeAndCardNameMap = new HashMap<String,String>();
		
		//卡物理类型代码，对应的名称
		Map<String,String> cardTypeCodeAndNameMap = new HashMap<String,String>();
		
		for(int j=0;j<citizenCardNoArray.length;j++){
			cardNoAndStocTypeMap.put(citizenCardNoArray[j], stockTypeArray[j]);
		}
		
		
		//通过市民卡号列表查询出cardData集合
		citizenCardNoList = Arrays.asList(citizenCardNoArray);
		List<CardData> cardDataList = cdm.queryCardDataByCitizenCardNoList(citizenCardNoList);
		for(int i=0;i<cardDataList.size();i++){
			CardData cardDataObj = cardDataList.get(i);
			String cardPCode = cardDataObj.getCardpCode();
			String citizenCardNo = cardDataObj.getCitizenCardNo();
			String physicType = cardDataObj.getCardPhysicalType();
			String stockType = cardNoAndStocTypeMap.get(citizenCardNo);
			String cardPCodeAndType = cardPCode+"#"+physicType+"#"+stockType;
			//卡控制列表
			cardControlIdList.add(String.valueOf(cardDataObj.getCardDataId()));
			cardPCodeList.add(cardPCode);
			if(cardPCodeAndAmount.containsKey(cardPCodeAndType)){
				Integer amount = cardPCodeAndAmount.get(cardPCodeAndType);
				cardPCodeAndAmount.put(cardPCodeAndType, amount+1);
			}else{
				cardPCodeAndAmount.put(cardPCodeAndType, 1);
			}
			
		}
		logger.debug("cardPCodeAndAmount==>"+cardPCodeAndAmount);
		HashSet<String> h = new HashSet<String>(cardPCodeList);   
		cardPCodeList.clear();   
		cardPCodeList.addAll(h);   
		List<CardProdunctDefinition> cardProDefObj = cpdm.queryCardNameByCode(cardPCodeList);
		for(int m=0;m<cardProDefObj.size();m++){
			CardProdunctDefinition cardDef = cardProDefObj.get(m);
			cardCodeAndCardNameMap.put(cardDef.getCardpCode(), cardDef.getCardpName());
		}
		//查询卡片物理类型名称
		List<CardPhysicsType> cardPhysicTypeList = cptm.queryAllCardPhysicsType();
		for(int n=0;n<cardPhysicTypeList.size();n++){
			CardPhysicsType cardTypeObj = cardPhysicTypeList.get(n);
			cardTypeCodeAndNameMap.put(cardTypeObj.getCardTypeCode(), cardTypeObj.getCardTypeName());
		}
		
		Integer totalAmount = cardControlIdList.size();
	
		
		//入库记录
		String storageNo = inventoryRecordNoUtil.getStorageNo();
		logger.debug("新的出入库号==>"+storageNo);
		StorageReg sr=new StorageReg();
		sr.setStorageNo(storageNo);
		sr.setBussinessNo("");
		sr.setStorageDetailNo("");
		sr.setAmount(totalAmount);
		//入库模式 15
		sr.setStorageMode("06");
		//入库为1
		sr.setStorageType("0");
		sr.setStorageReason("柜员归还入库");
		sr.setStorageDate(DateAndStampUtil.getCurrentDate());
		sr.setRevocationDate("");
		sr.setRevocationOperatorNo("");
		sr.setRevocationBranchNo("");
		sr.setStartNo("");
		sr.setEndNo("");
		sr.setStorageStatus("1");
		sr.setSourcePosition("2");
		sr.setDesPosition("2");
		//这边先写死，来源网点,中心库
		sr.setSourceBranchNo(branchNo);
		sr.setDesBranchNo(branchNo);
		sr.setIsReceive("");
		sr.setBothSeqNo("");
		sr.setDataInMode("0");
		sr.setOperatorNo(opeNo);
		sr.setOperateBranchNo(branchNo);
		sr.setInputDate(DateAndStampUtil.getCurrentDate());
		sr.setRemark("");
		sr.setRevocationBussinessNo("");
		logger.debug("sr==>"+sr.toString());
		//插入出入库登记表
		srm.insert(sr);
		
		//入库明细
		String detailNo = getDetailNo();
		StorageDetail sd=new StorageDetail();
		
		sd.setStorageDetailNo(detailNo);
		sd.setStorageNo(storageNo);
		sd.setAmount(totalAmount);
		logger.debug("sd==>"+sd);
		sdm.insert(sd);//更新出入库明细表
		
		//库存汇总
		//库存明细
		String ID = stockdm.queryMaxDetailId();
		if("".equals(ID)||null==ID){
				ID = "1";
		}
		int id = Integer.parseInt(ID)+1;
		
		Set<Map.Entry<String,Integer>> entrySet = cardPCodeAndAmount.entrySet();
		for(Map.Entry<String,Integer> entry:entrySet){
			StockSum ss = new StockSum();
			String cardPCodeAndType = entry.getKey();
			String[] cardArray = cardPCodeAndType.split("#");
			String cardCode = cardArray[0];
			String cardPhysicType = cardArray[1];
			String cardStockType = cardArray[2];
			String cardPName = cardCodeAndCardNameMap.get(cardCode)+cardTypeCodeAndNameMap.get(cardPhysicType);
			cardPNameList.add(cardPName);
			amountList.add(entry.getValue());
			ss.setBranchNo(branchNo);
			ss.setCardpCode(cardCode);
			ss.setStockPosition("2");
			ss.setCardStockType(cardStockType);
			ss.setCardPhysicType(cardPhysicType);
				
			String stockSumID = ssm.queryStockSumNoByCardPCode(ss);
			logger.debug("库存汇总ID==>"+stockSumID);	
			String stockSumIDToUpdate = null;
			if("".equals(stockSumID) || stockSumID==null){
				//查找库存汇总表中最大的ID号
				String newID = null;
				String maxStockSumID = ssm.queryMaxStockSumID();
				if(!"".equals(maxStockSumID)&&maxStockSumID!=null){
					Integer no = Integer.parseInt(maxStockSumID.substring(4))+1;
					//取得的数字的长度
					int numLength = String.valueOf(no).length();
					//判断取得的数字长度与字段长度，如果小于字段长度，那么说明字段的数字位是以0开头的，需要补位
					int addZero = maxStockSumID.substring(4).length()-numLength;
					if(addZero>0){
						int len = maxStockSumID.substring(4).length();
						newID = "KCHZ"+String.format("%0" + len + "d", no);
					}
					if(addZero==0){
						newID = "KCHZ"+no;
					}
				}else{
					newID = "KCHZ000001";
				}
				
				logger.debug("库存出入库汇总号是==>"+newID);
				
				ss.setStockSumId(newID);
				ss.setTotalNum(0);
				ss.setCurrNum(0);
				ss.setRealOutNum(0);
				ss.setOutSum(0);
				ssm.insertNewStockInfo(ss);
				stockSumIDToUpdate = newID;
			}else{
				stockSumIDToUpdate = stockSumID;
			}
			//更新前，锁死要更新的行
			StockSum stockSumObjTemp = ssm.queryStockSumBySumId(stockSumIDToUpdate);
			ss.setLastOperator(opeNo);
			ss.setLastModDate(DateAndStampUtil.getCurrentDate());
			ss.setOperatorAmount(entry.getValue());
			ss.setStockSumId(stockSumID);
			logger.debug("ss==>"+ss.toString());
			ssm.updateStockSumByOutCancel(ss);

			
			
			StockDetail stockDetail = new StockDetail();
			stockDetail.setStockSumId(stockSumIDToUpdate);
			stockDetail.setStockDetailId(id);
			stockDetail.setTaskNo("");
		//制卡返回文件号，这里不需要，可以从入库出库明细中查询
		//	stockDetail.setMakecardReturnNo(makeCardNoList.get(i));
			stockDetail.setItemAttrVal03("");
			stockDetail.setItemAttrVal04("");
			stockDetail.setItemAttrVal05("");
			stockDetail.setAmount(entry.getValue());
			stockDetail.setInStockStat("0");
			stockDetail.setLstInNo(storageNo);
			stockDetail.setLstOutNo("");
			stockDetail.setLstInDate("");
			stockDetail.setLstOutDate(DateAndStampUtil.getCurrentDate());
			stockDetail.setLstInOperator("");
			stockDetail.setLstOutOperator(opeNo);
			stockDetail.setFileDate("");
			stockDetail.setFileFlag("");
			logger.debug("stockDetail===>"+stockDetail.toString());
			stockdm.insert(stockDetail);
			id++;
		}
		
		//插入卡管理表
		//6.卡过程表
		List<CardData> cardDataObjList = cdm.queryCardDataByCardControlIdList(cardControlIdList);
		//卡过程表
		//查询出卡号
		Date currentDate = new Date();
		List<CardManage> cardMagList = new ArrayList<CardManage>();
		List<CardControl> cardControlObjList = new ArrayList<CardControl>();
		for(int i=0;i<cardDataObjList.size();i++){
			CardManage cme = new CardManage();
			CardControl cardControlObj = new CardControl();
			String currProcId = UUID.randomUUID().toString().replace("-", "");
			cme.setProcessId(currProcId);
			cme.setApplyBranchNo(branchNo);
			cme.setApplyDate(new Date());
			cme.setApplyTellerNo(opeNo);
			cme.setBusinessNo("");
			cme.setProcessCode(CardContants.CARD_PROC_RTNBYEMP);
			cme.setProcessName("柜员归还网点库管");
			cme.setCitizenCardNo(cardDataObjList.get(i).getCitizenCardNo());
			cme.setCardPosition(CardContants.CARD_POSITION_NET_DOT);
		//	cme.setCardStatus(CardContants.CARD_STATE_DISABLED);
		//	cme.setApplyWay("");// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
			cardMagList.add(cme);
			cardControlObj.setCurrProcId(currProcId);
			cardControlObj.setCardPosition("2");
			cardControlObj.setCardPoaitionByEmp("");
			cardControlObj.setLastDate(currentDate);
			cardControlObj.setLastOperator(opeNo);
			cardControlObj.setCardControlId(cardDataObjList.get(i).getCardDataId());
			cardControlObjList.add(cardControlObj);
			
		}
		cmm.batchInsert(cardMagList);
		
		//更新控制ID,先进行行加锁
		List<String> cardPositionList = cardControlMap.queryCardPositionByControlId(cardControlIdList);
		cardControlMap.updateByControlIDAtReturnCard(cardControlObjList);
		
		//打印参数
		//出入库号
		resultMap.put("storageNo", storageNo);
		//网点号
		resultMap.put("branchNo", branchNo);
		//出入库总数量(因为这里是只选择一项，数量暂时这么编辑，后期需要改正)
		resultMap.put("totalAmount", String.valueOf(totalAmount));
		//出入库日期
		resultMap.put("curDate", DateAndStampUtil.getCurrentDate());
		//清单明细抬头
		resultMap.put("title", "柜员归还卡片清单");
		//卡产品名称列表
		
		resultMap.put("cardPNameList", cardPNameList);
		//制卡批号列表
		resultMap.put("makeCardNoList", "");
		//制卡商名称列表
		resultMap.put("companyList", "");
		//每个批号的数量列表
		resultMap.put("amountList", amountList);
		//凭证类型
		resultMap.put("credential_type", "storage");
		logger.debug("resultMap==>"+resultMap);
		
		createStoragePDF(resultMap);
		
		Map<String,Object> rMap = new HashMap<String,Object>();
		rMap.put("ipAddress", IP_ADDRESS);
		rMap.put("storageNo", storageNo);
		rMap.put("credential_type", "storage");
		rMap.put("title", "柜员归还卡片清单");
		return rMap;
	}

	@Override
	public Map<String, Object> saveSurplusCardRecords(HttpServletRequest request) {
		
		String[] cardPCodeArray = request.getParameterValues("cardCodeBySurplus");
		String[] cardTypeArray = request.getParameterValues("cardTypeBySurplus");
		String[] citizenCardNoArray = request.getParameterValues("cardNoBySurplus");
		String[] stockTypeArray = request.getParameterValues("stockTypeBySurplus");
		String branchNo = request.getParameter("branchNoBySurplus");
		String opeNo = request.getParameter("empNoBySurplus");
	
		//返回的打印用参数map
		//卡产品代码列表
		List<String> cardPCodeList = new ArrayList<String>();
		//市民卡号代码，数量列表
		List<String> citizenCardNoList = new ArrayList<String>();
		//卡产品代码对应数量（卡产品代码，数量）
		Map<String,Integer> cardPCodeAndAmount = new HashMap<String,Integer>();
		//卡产品名称列表
		List<String> cardPNameList = new ArrayList<String>();
		//卡产品数量列表
		List<Integer> amountList = new ArrayList<Integer>();
		//卡控制ID列表
		List<String> cardControlIdList = new ArrayList<String>();
		
		//市民卡与库存卡片种类的map
		Map<String,String> cardNoAndStocTypeMap = new HashMap<String,String>();
		//卡产品代码对应的卡产品名称map
		Map<String,String> cardCodeAndCardNameMap = new HashMap<String,String>();
		
		//卡物理类型代码，对应的名称
		Map<String,String> cardTypeCodeAndNameMap = new HashMap<String,String>();
		
		for(int j=0;j<citizenCardNoArray.length;j++){
			cardNoAndStocTypeMap.put(citizenCardNoArray[j], stockTypeArray[j]);
		}
		
		
		//通过市民卡号列表查询出cardData集合
		citizenCardNoList = Arrays.asList(citizenCardNoArray);
		List<CardData> cardDataList = cdm.queryCardDataByCitizenCardNoList(citizenCardNoList);
		for(int i=0;i<cardDataList.size();i++){
			CardData cardDataObj = cardDataList.get(i);
			String cardPCode = cardDataObj.getCardpCode();
			String citizenCardNo = cardDataObj.getCitizenCardNo();
			String physicType = cardDataObj.getCardPhysicalType();
			String stockType = cardNoAndStocTypeMap.get(citizenCardNo);
			String cardPCodeAndType = cardPCode+"#"+physicType+"#"+stockType;
			//卡控制列表
			cardControlIdList.add(String.valueOf(cardDataObj.getCardDataId()));
			cardPCodeList.add(cardPCode);
			if(cardPCodeAndAmount.containsKey(cardPCodeAndType)){
				Integer amount = cardPCodeAndAmount.get(cardPCodeAndType);
				cardPCodeAndAmount.put(cardPCodeAndType, amount+1);
			}else{
				cardPCodeAndAmount.put(cardPCodeAndType, 1);
			}
			
		}
		
		logger.debug("cardPCodeAndAmount==>"+cardPCodeAndAmount);
		HashSet<String> h = new HashSet<String>(cardPCodeList);   
		cardPCodeList.clear();   
		cardPCodeList.addAll(h);   
		List<CardProdunctDefinition> cardProDefObj = cpdm.queryCardNameByCode(cardPCodeList);
		for(int m=0;m<cardProDefObj.size();m++){
			CardProdunctDefinition cardDef = cardProDefObj.get(m);
			cardCodeAndCardNameMap.put(cardDef.getCardpCode(), cardDef.getCardpName());
		}
		//查询卡片物理类型名称
		List<CardPhysicsType> cardPhysicTypeList = cptm.queryAllCardPhysicsType();
		for(int n=0;n<cardPhysicTypeList.size();n++){
			CardPhysicsType cardTypeObj = cardPhysicTypeList.get(n);
			cardTypeCodeAndNameMap.put(cardTypeObj.getCardTypeCode(), cardTypeObj.getCardTypeName());
		}
		
		Integer totalAmount = cardControlIdList.size();
		
		//出入库记录
		String storageNo = inventoryRecordNoUtil.getStorageNo();
		logger.debug("新的出入库号==>"+storageNo);
		StorageReg sr=new StorageReg();
		sr.setStorageNo(storageNo);
		sr.setBussinessNo("");
		sr.setStorageDetailNo("");
		sr.setAmount(totalAmount);
		//入库模式 15
		sr.setStorageMode("05");
		//入库为1
		sr.setStorageType("0");
		sr.setStorageReason("盘盈入库");
		sr.setStorageDate(DateAndStampUtil.getCurrentDate());
		sr.setRevocationDate("");
		sr.setRevocationOperatorNo("");
		sr.setRevocationBranchNo("");
		sr.setStartNo("");
		sr.setEndNo("");
		sr.setStorageStatus("0");
		sr.setSourcePosition("2");
		sr.setDesPosition("2");
		//这边先写死，来源网点,中心库
		sr.setSourceBranchNo(branchNo);
		sr.setDesBranchNo(branchNo);
		sr.setIsReceive("");
		sr.setBothSeqNo("");
		sr.setDataInMode("0");
		sr.setOperatorNo(opeNo);
		sr.setOperateBranchNo(branchNo);
		sr.setInputDate(DateAndStampUtil.getCurrentDate());
		sr.setRemark("");
		sr.setRevocationBussinessNo("");
		logger.debug("sr==>"+sr.toString());
		//插入出入库登记表
		srm.insert(sr);
		
		
		//入库明细
		String detailNo = getDetailNo();
		StorageDetail sd=new StorageDetail();
		
		sd.setStorageDetailNo(detailNo);
		sd.setStorageNo(storageNo);
		sd.setAmount(totalAmount);
		logger.debug("sd==>"+sd);
		sdm.insert(sd);//更新出入库明细表
		
		//库存汇总
		String ID = stockdm.queryMaxDetailId();
		if("".equals(ID)||null==ID){
				ID = "1";
		}
		int id = Integer.parseInt(ID)+1;
		Set<Map.Entry<String,Integer>> entrySet = cardPCodeAndAmount.entrySet();
		for(Map.Entry<String,Integer> entry:entrySet){
			StockSum ss = new StockSum();
			String cardPCodeAndType = entry.getKey();
			String[] cardArray = cardPCodeAndType.split("#");
			String cardCode = cardArray[0];
			String cardPhysicType = cardArray[1];
			String cardStockType = cardArray[2];
			String cardPName = cardCodeAndCardNameMap.get(cardCode)+cardTypeCodeAndNameMap.get(cardPhysicType);
			cardPNameList.add(cardPName);
			amountList.add(entry.getValue());
			ss.setBranchNo(branchNo);
			ss.setCardpCode(cardCode);
			ss.setCardpName(cardPName);
			ss.setStockPosition("2");
			ss.setCardStockType(cardStockType);
			ss.setCardPhysicType(cardPhysicType);
			
			String stockSumID = ssm.queryStockSumNoByCardPCode(ss);
			
			logger.debug("库存汇总ID==>"+stockSumID);
			String stockSumIDToUpdate = null;
			if("".equals(stockSumID) || stockSumID==null){
				//查找库存汇总表中最大的ID号
				String newID = null;
				String maxStockSumID = ssm.queryMaxStockSumID();
				if(!"".equals(maxStockSumID)&&maxStockSumID!=null){
					Integer no = Integer.parseInt(maxStockSumID.substring(4))+1;
					//取得的数字的长度
					int numLength = String.valueOf(no).length();
					//判断取得的数字长度与字段长度，如果小于字段长度，那么说明字段的数字位是以0开头的，需要补位
					int addZero = maxStockSumID.substring(4).length()-numLength;
					if(addZero>0){
						int len = maxStockSumID.substring(4).length();
						newID = "KCHZ"+String.format("%0" + len + "d", no);
					}
					if(addZero==0){
						newID = "KCHZ"+no;
					}
				}else{
					newID = "KCHZ000001";
				}
				
				logger.debug("库存出入库汇总号是==>"+newID);
				
				ss.setStockSumId(newID);
				ss.setTotalNum(0);
				ss.setCurrNum(0);
				ss.setRealOutNum(0);
				ss.setOutSum(0);
				ssm.insertNewStockInfo(ss);
				stockSumIDToUpdate = newID;
			}else{
				stockSumIDToUpdate = stockSumID;
			}
			
			//更新前，锁死要更新的行
			StockSum stockSumObjTemp = ssm.queryStockSumBySumId(stockSumIDToUpdate);
			ss.setLastOperator(opeNo);
			ss.setLastModDate(DateAndStampUtil.getCurrentDate());
			ss.setOperatorAmount(entry.getValue());
			
			logger.debug("ss==>"+ss.toString());
			ssm.updateStockSumByIcoming(ss);
			
			StockDetail stockDetail = new StockDetail();
			stockDetail.setStockSumId(stockSumIDToUpdate);
			stockDetail.setStockDetailId(id);
			stockDetail.setTaskNo("");
		//	stockDetail.setMakecardReturnNo(makeCardNoList.get(i));
			stockDetail.setItemAttrVal03("");
			stockDetail.setItemAttrVal04("");
			stockDetail.setItemAttrVal05("");
			stockDetail.setAmount(entry.getValue());
			stockDetail.setInStockStat("0");
			stockDetail.setLstInNo(storageNo);
			stockDetail.setLstOutNo("");
			stockDetail.setLstInDate("");
			stockDetail.setLstOutDate(DateAndStampUtil.getCurrentDate());
			stockDetail.setLstInOperator("");
			stockDetail.setLstOutOperator(opeNo);
			stockDetail.setFileDate("");
			stockDetail.setFileFlag("");
			logger.debug("stockDetail===>"+stockDetail.toString());
			stockdm.insert(stockDetail);
			id++;
		}
		
		//插入卡管理表
		List<CardData> cardDataObjList = cdm.queryCardDataByCardControlIdList(cardControlIdList);
		//卡过程表
		Date currentDate = new Date();
		List<CardManage> cardMagList = new ArrayList<CardManage>();
		List<CardControl> cardControlObjList = new ArrayList<CardControl>();
		for(int i=0;i<cardDataObjList.size();i++){
			CardManage cme = new CardManage();
			CardControl cardControlObj = cardControlMap.queryCardControlByCitizenCardNo(cardDataObjList.get(i).getCitizenCardNo());
			String currProcId = UUID.randomUUID().toString().replace("-", "");
			cme.setProcessId(currProcId);
			cme.setApplyBranchNo(branchNo);
			cme.setApplyDate(new Date());
			cme.setApplyTellerNo(opeNo);
			cme.setBusinessNo("");
			cme.setProcessCode(CardContants.CARD_PROC_SURPLUSINCOM);
			cme.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_SURPLUSINCOM));
			cme.setCitizenCardNo(cardDataObjList.get(i).getCitizenCardNo());
			cme.setCardPosition(CardContants.CARD_POSITION_NET_DOT);
		//	cme.setCardStatus(CardContants.CARD_STATE_DISABLED);
		//	cme.setApplyWay("");// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
			cardMagList.add(cme);
			cardControlObj.setCurrProcId(currProcId);
			cardControlObj.setLastDate(currentDate);
			cardControlObj.setLastOperator(opeNo);
			cardControlObj.setCardPosition(CardContants.CARD_POSITION_NET_DOT);
			cardControlObjList.add(cardControlObj);
		}
		cmm.batchInsert(cardMagList);
		
		
		
		//再次更新卡控制卡位置状态
		List<String> cardPositionList = cardControlMap.queryCardPositionByControlId(cardControlIdList);
		cardControlMap.updateByControlIDAtReturnCard(cardControlObjList);
		

		
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		//打印参数
		//出入库号
		resultMap.put("storageNo", storageNo);
		//网点号
		resultMap.put("branchNo", branchNo);
		//出入库总数量(因为这里是只选择一项，数量暂时这么编辑，后期需要改正)
		resultMap.put("totalAmount", String.valueOf(totalAmount));
		//出入库日期
		resultMap.put("curDate", DateAndStampUtil.getCurrentDate());
		//清单明细抬头
		resultMap.put("title", "盘盈入库清单");
		//卡产品名称列表
		
		resultMap.put("cardPNameList", cardPNameList);
		//制卡批号列表
		resultMap.put("makeCardNoList", "");
		//制卡商名称列表
		resultMap.put("companyList", "");
		//每个批号的数量列表
		resultMap.put("amountList", amountList);
		//凭证类型
		resultMap.put("credential_type", "storage");
		logger.debug("resultMap==>"+resultMap);

		return resultMap;
	}

	@Override
	public Map<String, Object> saveDeficientOutboundRecords(HttpServletRequest request) {
		
		String[] cardPCodeArray = request.getParameterValues("cardCodeByDeficientOutbound");
		String[] cardTypeArray = request.getParameterValues("cardTypeByDeficientOutbound");
		String[] citizenCardNoArray = request.getParameterValues("cardNoByDeficientOutbound");
		String[] stockTypeArray = request.getParameterValues("stockTypeByDeficientOutbound");
		
		String branchNo = request.getParameter("branchNoByDishDeficientOutbound");
		String opeNo = request.getParameter("empNoByDishDeficientOutbound");
		
		//返回的打印用参数map
		//卡产品代码列表
		List<String> cardPCodeList = new ArrayList<String>();
		//市民卡号代码，数量列表
		List<String> citizenCardNoList = new ArrayList<String>();
		//卡产品代码对应数量（卡产品代码，数量）
		Map<String,Integer> cardPCodeAndAmount = new HashMap<String,Integer>();
		//卡产品名称列表
		List<String> cardPNameList = new ArrayList<String>();
		//卡控制ID列表
		List<String> cardControlIdList = new ArrayList<String>();
		//卡产品数量列表
		List<Integer> amountList = new ArrayList<Integer>();
		//市民卡与库存卡片种类的map
		Map<String,String> cardNoAndStocTypeMap = new HashMap<String,String>();
		//卡产品代码对应的卡产品名称map
		Map<String,String> cardCodeAndCardNameMap = new HashMap<String,String>();
				
		//卡物理类型代码，对应的名称
		Map<String,String> cardTypeCodeAndNameMap = new HashMap<String,String>();
		
		for(int j=0;j<citizenCardNoArray.length;j++){
			cardNoAndStocTypeMap.put(citizenCardNoArray[j], stockTypeArray[j]);
		}
		
		//通过市民卡号列表查询出cardData集合
		citizenCardNoList = Arrays.asList(citizenCardNoArray);
		List<CardData> cardDataList = cdm.queryCardDataByCitizenCardNoList(citizenCardNoList);
		for(int i=0;i<cardDataList.size();i++){
			CardData cardDataObj = cardDataList.get(i);
			String cardPCode = cardDataObj.getCardpCode();
			String citizenCardNo = cardDataObj.getCitizenCardNo();
			String physicType = cardDataObj.getCardPhysicalType();
			String stockType = cardNoAndStocTypeMap.get(citizenCardNo);
			String cardPCodeAndType = cardPCode+"#"+physicType+"#"+stockType;
			//卡控制列表
			cardControlIdList.add(String.valueOf(cardDataObj.getCardDataId()));
			cardPCodeList.add(cardPCode);
			if(cardPCodeAndAmount.containsKey(cardPCodeAndType)){
				Integer amount = cardPCodeAndAmount.get(cardPCodeAndType);
				cardPCodeAndAmount.put(cardPCodeAndType, amount+1);
			}else{
				cardPCodeAndAmount.put(cardPCodeAndType, 1);
			}
			
		}
		logger.debug("cardPCodeAndAmount==>"+cardPCodeAndAmount);
		HashSet<String> h = new HashSet<String>(cardPCodeList);   
		cardPCodeList.clear();   
		cardPCodeList.addAll(h);   
		List<CardProdunctDefinition> cardProDefObj = cpdm.queryCardNameByCode(cardPCodeList);
		for(int m=0;m<cardProDefObj.size();m++){
			CardProdunctDefinition cardDef = cardProDefObj.get(m);
			cardCodeAndCardNameMap.put(cardDef.getCardpCode(), cardDef.getCardpName());
		}
		//查询卡片物理类型名称
		List<CardPhysicsType> cardPhysicTypeList = cptm.queryAllCardPhysicsType();
		for(int n=0;n<cardPhysicTypeList.size();n++){
			CardPhysicsType cardTypeObj = cardPhysicTypeList.get(n);
			cardTypeCodeAndNameMap.put(cardTypeObj.getCardTypeCode(), cardTypeObj.getCardTypeName());
		}
		
		Integer totalAmount = cardControlIdList.size();
		
		/*for(int i=0;i<cardPCodeArray.length;i++){
			Integer amount = 1;
			citizenCardNoList.add(citizenCardNoArray[i]);
			if(cardPCodeList.contains(cardPCodeArray[i])){
				amount = cardPCodeAndAmount.get(cardPCodeArray[i])+1;
			}else{
				cardPCodeList.add(cardPCodeArray[i]);
				cardPNameList.add(cpdm.queryCardPCode(cardPCodeArray[i]).getCardpName());
			}
			cardPCodeAndAmount.put(cardPCodeArray[i], amount);
		}
		for(int j=0;j<cardPCodeList.size();j++){
			amountList.add(String.valueOf(cardPCodeAndAmount.get(cardPCodeList.get(j))));
		}
		
		Integer totalAmount = citizenCardNoList.size();*/
		
		
		//出入库记录
		String storageNo = inventoryRecordNoUtil.getStorageNo();
		logger.debug("新的出入库号==>"+storageNo);
		StorageReg sr=new StorageReg();
		sr.setStorageNo(storageNo);
		sr.setBussinessNo("");
		sr.setStorageDetailNo("");
		sr.setAmount(totalAmount);
		//入库模式 15
		sr.setStorageMode("14");
		//入库为1
		sr.setStorageType("1");
		sr.setStorageReason("盘亏出库");
		sr.setStorageDate(DateAndStampUtil.getCurrentDate());
		sr.setRevocationDate("");
		sr.setRevocationOperatorNo("");
		sr.setRevocationBranchNo("");
		sr.setStartNo("");
		sr.setEndNo("");
		sr.setStorageStatus("1");
		sr.setSourcePosition("2");
		sr.setDesPosition("2");
		//这边先写死，来源网点,中心库
		sr.setSourceBranchNo(branchNo);
		sr.setDesBranchNo(branchNo);
		sr.setIsReceive("");
		sr.setBothSeqNo("");
		sr.setDataInMode("0");
		sr.setOperatorNo(opeNo);
		sr.setOperateBranchNo(branchNo);
		sr.setInputDate(DateAndStampUtil.getCurrentDate());
		sr.setRemark("");
		sr.setRevocationBussinessNo("");
		logger.debug("sr==>"+sr.toString());
		//插入出入库登记表
		srm.insert(sr);
		
		
		//入库明细
		String detailNo = getDetailNo();
		StorageDetail sd=new StorageDetail();
		
		sd.setStorageDetailNo(detailNo);
		sd.setStorageNo(storageNo);
		sd.setAmount(totalAmount);
		logger.debug("sd==>"+sd);
		sdm.insert(sd);//更新出入库明细表
		
		//库存汇总
		String ID = stockdm.queryMaxDetailId();
		if("".equals(ID)||null==ID){
				ID = "1";
		}
		int id = Integer.parseInt(ID)+1;
		Set<Map.Entry<String,Integer>> entrySet = cardPCodeAndAmount.entrySet();
		for(Map.Entry<String,Integer> entry:entrySet){
			StockSum ss = new StockSum();
			String cardPCodeAndType = entry.getKey();
			String[] cardArray = cardPCodeAndType.split("#");
			String cardCode = cardArray[0];
			String cardPhysicType = cardArray[1];
			String cardStockType = cardArray[2];
			String cardPName = cardCodeAndCardNameMap.get(cardCode)+cardTypeCodeAndNameMap.get(cardPhysicType);
			cardPNameList.add(cardPName);
			amountList.add(entry.getValue());
			ss.setBranchNo(branchNo);
			ss.setCardpCode(cardCode);
			ss.setStockPosition("2");
			ss.setCardPhysicType(cardPhysicType);
			ss.setCardStockType(cardStockType);
			//现根据卡产品代码，网点编号，stockStatus=1条件查询库中是否有数据，
			//如果没有则插入一条数据，然后再更新
			
			String stockSumID = ssm.queryStockSumNoByCardPCode(ss);
			logger.debug("库存汇总ID==>"+stockSumID);
			
			//更新前，锁死要更新的行
			StockSum stockSumObjTemp = ssm.queryStockSumBySumId(stockSumID);
			ss.setLastOperator(opeNo);
			ss.setLastModDate(DateAndStampUtil.getCurrentDate());
			ss.setOperatorAmount(entry.getValue());
			
			logger.debug("ss==>"+ss.toString());
			//柜员领用也算出库，sql文可以和网点配送到中心库的sql文使用一个
			ssm.updateStockSumByDistributeToCenter(ss);

			
			
			StockDetail stockDetail = new StockDetail();
			stockDetail.setStockSumId(stockSumID);
			stockDetail.setStockDetailId(id);
			stockDetail.setTaskNo("");
		//制卡返回文件号，这里不需要，可以从入库出库明细中查询
		//	stockDetail.setMakecardReturnNo(makeCardNoList.get(i));
			stockDetail.setItemAttrVal03("");
			stockDetail.setItemAttrVal04("");
			stockDetail.setItemAttrVal05("");
			stockDetail.setAmount(entry.getValue());
			stockDetail.setInStockStat("1");
			stockDetail.setLstInNo("");
			stockDetail.setLstOutNo(storageNo);
			stockDetail.setLstInDate("");
			stockDetail.setLstOutDate(DateAndStampUtil.getCurrentDate());
			stockDetail.setLstInOperator("");
			stockDetail.setLstOutOperator(opeNo);
			stockDetail.setFileDate("");
			stockDetail.setFileFlag("");
			logger.debug("stockDetail===>"+stockDetail.toString());
			stockdm.insert(stockDetail);
			id++;
		}
		
		
		//更新卡控制状态
		//更新控制ID,先进行行加锁
		List<String> cardPositionList = cardControlMap.queryCardPositionByControlId(cardControlIdList);
		String position = "9";
		//20181214修改
	//	cardControlMap.updateByControlIDAtReturnCard(cardControlIdList,opeNo,position);
		
		//组装打印参数
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("storageNo", storageNo);
		//网点号
		resultMap.put("branchNo", branchNo);
		//出入库总数量(因为这里是只选择一项，数量暂时这么编辑，后期需要改正)
		resultMap.put("totalAmount", String.valueOf(totalAmount));
		//出入库日期
		resultMap.put("curDate", DateAndStampUtil.getCurrentDate());
		//清单明细抬头
		resultMap.put("title", "盘亏出库清单");
		//卡产品名称列表
		
		resultMap.put("cardPNameList", cardPNameList);
		//制卡批号列表
		resultMap.put("makeCardNoList", "");
		//制卡商名称列表
		resultMap.put("companyList", "");
		//每个批号的数量列表
		resultMap.put("amountList", amountList);
		//凭证类型
		resultMap.put("credential_type", "storage");
		logger.debug("resultMap==>"+resultMap);
		return resultMap;
	}

	@Override
	public List<StockSum> queryStockSum(HttpServletRequest request) {
		/*ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}*/
	//	String branchNo = activeUser.getBranchNo();
		String branchNo = request.getParameter("branchNameByQueryInventory");
		String cardPCode = request.getParameter("cardPNameByQueryInventory");
		String userNo = request.getParameter("empNoByQureryInventory");
	//	String branchNo = request.getParameter("branchNoByQueryInventory");
		logger.debug("branchNo==>"+branchNo);
		logger.debug("cardPCode==>"+cardPCode);
		//查询库存表是否有信息，如果有，继续，没有返回
		int stockCount = ssm.queryStockSumTotalCounts();
		List<StockSum> stockSumList = new ArrayList<StockSum>();
		if(stockCount>0){
			stockSumList = ssm.queryInventory(branchNo,cardPCode);
			for(int i=0;i<stockSumList.size();i++){
				logger.debug(i+"==>"+stockSumList.get(i));
			}
		}
		return stockSumList;
	}

	@Override
	public List<QueryIncomingAndOutGoing> queryIncomingAndOutgoingInfo(HttpServletRequest request) {
		String branchNo = request.getParameter("branchNoByLoad");
		logger.debug("branchNo===>"+branchNo);
		if("10000000".equals(branchNo)){
			branchNo="";
		}else{
			String branchName = request.getParameter("branchNameByQueryIncomingAndOutgoing");
			//查询出对应的网点编号
			if("".equals(branchName)||branchName==null){
				branchNo = "";
			}else{
				branchNo = String.valueOf(orgm.queryOrgByOrgName(branchName).getOrgNo());
			}
		}

		String cardPCode = request.getParameter("cardPNameByQueryIncomingAndOutgoing");
		String dateFrom = request.getParameter("dateYMFromByIncomingAndOutgoing").replace("-", "");
		String dateTo = request.getParameter("dateYMToByIncomingAndOutgoing").replace("-", "");
		logger.debug("branchNo==>"+branchNo);
		logger.debug("cardPCode==>"+cardPCode);
		logger.debug("dateFrom==>"+dateFrom);
		logger.debug("dateTo==>"+dateTo);
		List<QueryIncomingAndOutGoing> stockSumObj = new ArrayList<QueryIncomingAndOutGoing>();
		
		stockSumObj = ssm.queryIncomeAndOutgoingInfo(branchNo,cardPCode,dateFrom,dateTo);
		logger.debug("stockSumObj==>"+stockSumObj);
		return stockSumObj;
	}

	@Override
	@SystemServiceLog(description = "查询卡片信息")
	public Map<String, Object> queryCardInfoByCitizenCardNo(HttpServletRequest request) throws InventoryException {
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		String currentBranchNo = activeUser.getBranchNo();
		String citizenCardNo = request.getParameter("citizenCardNo");
		logger.debug("citizenCardNo==>"+citizenCardNo);
		CardInfoAndCustomerInfo cardAndCustInfo = aorm.queryCardInfoByCitizenCardNo(citizenCardNo);
		//判断该卡的位置是否准确，如果是柜员处的卡片，判断该柜员所在的网点,如果是在网点，判断哪个网点
		//归还卡片入库，上缴废卡，上缴空白卡，盘盈入库，盘亏出库

		/*if("13".equals(storageMode)){
			if(!"0".equals(cardStatus)){
				throw new InventoryException("该卡不是空白或成品卡的新卡，不能作为新卡上缴出入库操作！");
			}
			if(!"2".equals(cardPosition)){
				throw new InventoryException("该卡位置信息有误，请联系管理员！不能作出入库操作");
			}else if(!currentBranchNo.equals(lastBranchNo)){
				//查询该卡的网点，与先操作员是否一致
				throw new InventoryException("该卡位置信息有误，请联系管理员！不能作出入库操作");
			}
		}
		if("15".equals(storageMode)){
			if("0".equals(cardStatus)){
				throw new InventoryException("该卡是空白或成品卡的新卡，不能作为废卡上缴出入库操作！");
			}
			if(!"2".equals(cardPosition)){
				throw new InventoryException("该卡位置信息有误，请联系管理员！不能作出入库操作");
			}else if(!currentBranchNo.equals(lastBranchNo)){
				//查询该卡的网点，与先操作员是否一致
				throw new InventoryException("该卡位置信息有误，请联系管理员！不能作出入库操作");
			}
		}*/
		
		//盘盈入库，实体卡片>系统库存，对卡片进行入库操作，不需要判断卡片的位置，入库时位置调整一致
		//盘亏出库，实体卡片<系统库存，需要按卡产品，不需要判断卡片的位置，入库时位置调整一致
		logger.debug("cardAndCustInfo==>"+cardAndCustInfo);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("cardAndCustInfo", cardAndCustInfo);
		map.put("activeUser", activeUser);
		return map;
	}

	@Override
	public List<CooperationCompany> queryCooperationCompanyByType(String companyType) throws ApplicationException {
		if (StringUtils.isEmpty(companyType)) {
			throw new ApplicationException(ErrorCode.OBJECT_IS_NULL,
					"companyType is null!!!");
		}
		return ccm.queryCooperationCompanyByType(companyType);
	}

	@Override
	public Map<String, Object> addReturnFileToPageTable(MultipartFile[] returnFilePath,HttpServletRequest request) throws IllegalStateException, IOException {
		String filePath = request.getParameter("filePathByReturnCard");
		String companyName = request.getParameter("companyName");
		List<String> filePathList = new ArrayList<String>();
		String[] filePaths ;
		if(filePath.indexOf(",")>0){
			filePaths = filePath.split(",");
			filePathList = Arrays.asList(filePaths);
		}else{
			filePathList.add(filePath);
		}
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("filePathList", filePathList);
		map.put("companyName", companyName);
		
		//将文件存放在工程目录下，作为临时文件
		String root = request.getSession().getServletContext().getRealPath("/");
		
		String applyBatchFileName = "";
		
		//验证不含txt
		boolean  b = false;
		for(MultipartFile  mf:returnFilePath){
			if(mf.getOriginalFilename().contains(".txt")){
				b = true;
				break;
			}
		}
		
		if(!b){
			map.put("statusCode", "300");
			map.put("message", "请选择txt导入");
			return map;//不包含excel
		}
		
		if (returnFilePath != null && returnFilePath.length > 0) {
			for (int i = 0; i < returnFilePath.length; i++) {
				MultipartFile file = returnFilePath[i];
				// 保存文件
					if (file.getOriginalFilename().endsWith(".txt")) {
						logger.debug("上传的文件名:[{}]", file.getOriginalFilename());
						//判断文件名是否正确
						String totalFileName = file.getOriginalFilename();
						int prefexIndex = totalFileName.indexOf(".txt");
						if(!checkFileUtil.checkFileName(totalFileName.substring(0,prefexIndex))){
							map.put("statusCode", "300");
							map.put("message", "该文件信息不正确，请核对后操作!");
							return map;
						}
						File ff = new File(root + PathContants.PROJECT_PATH_MAKECARDRETURNFILE);
						logger.debug("目录【{}】", ff.getAbsolutePath());
						if (!ff.exists()) {
							logger.debug("开始创建");
							ff.mkdirs();
						}
						File fi = new File(ff.getAbsolutePath() + File.separator + file.getOriginalFilename());

						//验证字段为空

						file.transferTo(fi);
						
						//判断文件格式是否正确
						if(!checkFileUtil.checkFileFormat(fi)){
							map.put("statusCode", "300");
							map.put("message", "该文件格式不正确，请核对后操作!");
							return map;
						}
						//判断文件是否已经导入过了
						logger.debug("totalFileName.substring(0,prefexIndex)==>"+totalFileName.substring(0,prefexIndex));
						if(!checkFileUtil.checkFileStatus(totalFileName.substring(0,prefexIndex))){
							if(fi.exists()){
								fi.delete();
							}
							map.put("statusCode", "300");
							map.put("message", "该文件已经入库或未申请，请重新选择文件!");
							return map;
						}
					} else{
						map.put("statusCode", "300");
						map.put("message", "文件不是txt格式");
						return map;
					}
			}
		}
		map.put("statusCode", "200");
		return map;
	}

	@Override
	public void returnFileImportRegister(HttpServletRequest request) {
		String root = request.getSession().getServletContext().getRealPath("/");
		String[] returnFilePath = request.getParameterValues("fileSourcePathToImport");
		String[] companyName = request.getParameterValues("companyNameByInventory");
		String targetBasePath = INCOMING_PATH;
		List<String> returnFilePathList = Arrays.asList(returnFilePath);
		
		List<String> companyNameList = Arrays.asList(companyName);
		List<String> templeList = new ArrayList<String>();
		templeList.addAll(companyNameList);
		for(int m=0;m<templeList.size();m++){
			logger.debug("companyNameList==>"+templeList.get(m));
		}
		List<String> companySet = listUtil.listToSet(templeList);
		for(int j=0;j<companySet.size();j++){
			String targetDir = targetBasePath+File.separator+companySet.get(j);
			File targetDirFile = new File(targetDir);
			if(!targetDirFile.exists()){
				targetDirFile.mkdirs();
			}
			logger.debug("targetDirFile==>"+targetDirFile.getName());
		}
		for(int i=0;i<returnFilePathList.size();i++){
			Integer indexTxt = returnFilePathList.get(i).lastIndexOf("\\");
			String sourceFileName = returnFilePathList.get(i).substring(indexTxt+1);
			String sourceFilePath = root + PathContants.PROJECT_PATH_MAKECARDRETURNFILE+File.separator+sourceFileName;
			String makeCardCompanyName = companyNameList.get(i);
			String targetFilePath = targetBasePath + File.separator+makeCardCompanyName;
			FileUtil.moveTotherFolders(sourceFilePath,targetFilePath);
		}
	}

	@Override
	@SystemServiceLog(description = "删除根目录下的文件")
	public void deleteReturnFileAtRoot(HttpServletRequest request) {
		String fileNameArray = request.getParameter("fileNameArray");
		String companyNameArray = request.getParameter("companyNameArray");	
		logger.debug("fileNameArray==>"+fileNameArray);
		logger.debug("companyNameArray==>"+companyNameArray);
		List<String> fileNameList = new ArrayList<String>();
		if(fileNameArray.indexOf("#")>0){
			String[] fileNames = fileNameArray.split("#");
			fileNameList = Arrays.asList(fileNames);
		}else{
			fileNameList.add(fileNameArray);
		}
		
		String root = request.getSession().getServletContext().getRealPath("/");
		String targetPath = root + PathContants.PROJECT_PATH_MAKECARDRETURNFILE;
		for(int i=0;i<fileNameList.size();i++){
			String targetFilePath = targetPath + File.separator + fileNameList.get(i);
			logger.debug("targetFilePath==>"+targetFilePath);
			File file = new File(targetFilePath);
			if(file.exists()){
				logger.debug("file==>"+file.getName());
				file.delete();
			}
			logger.debug("文件是否删除==>"+file.exists());
		}
	}

	@Override
	public Map<String,Object> queryStockDetailCardInfo(HttpServletRequest request) throws UnsupportedEncodingException {
		String param = URLDecoder.decode(request.getParameter("param"), "utf-8");
		logger.debug("param==>"+param);
		String cardStatus = null;
		String taskType = null;
		String[] itemArray = param.split("#");
		String cardPCode = itemArray[0];
		String cardPName = itemArray[1];
		String physicTypeCode = itemArray[2];
		String physicTypeName = itemArray[3];
		String cardStockType = itemArray[4];
		String stockPosition = itemArray[5];
		String stockPositionName = itemArray[6];
		String branchNo = itemArray[7];
		String branchName = itemArray[8];
		if("1".equals(cardStockType)){
			taskType = "2";
			cardStatus = "0";
		}else if("2".equals(cardStockType)){
			taskType = "1";
			cardStatus = "0";
		}else{
			cardStatus = "";
			taskType = "";
		}
		List<String> citizenCardNoList = ssm.queryCardNoByStockInfo(cardStatus,taskType,cardPCode,branchNo,stockPosition,physicTypeCode);
		
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("cardPName", cardPName);
		resultMap.put("physicTypeName", physicTypeName);
		resultMap.put("stockPositionName", stockPositionName);
		resultMap.put("branchName", branchName);
		resultMap.put("quantity", citizenCardNoList.size());
		String currentDate = DateAndStampUtil.getCurrentDate();
		resultMap.put("currentDate", currentDate);
		resultMap.put("citizenCardNoList", citizenCardNoList);
		
		
		return resultMap;
	}

	@Override
	@SystemServiceLog(description = "将html表格转换成pdf文件")
	public Map<String,String> createTableListPDF(HttpServletRequest request) throws Exception, Exception {
		ActiveUser activeUser = null;
		try{
			 activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		}
		catch(UnavailableSecurityManagerException e){
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
		}
		Integer currentEmpNo = activeUser.getUserNo();
		
		String[] tdContent = request.getParameterValues("tdContent[]");
		String tableHeader = request.getParameter("theadContent");
		String tableName = request.getParameter("tableName");
		logger.debug("tableHeader==>"+tableHeader);
		logger.debug("tableName==>"+tableName);
		logger.debug("tableContent==>"+Arrays.toString(tdContent));
		List<String> tableContent = Arrays.asList(tdContent);
		TableVo tableVoObj = new TableVo();
		tableVoObj.setTableHeader(tableHeader);
		tableVoObj.setTableContent(tableContent);
		tableVoObj.setTableTitle(tableName);
		PdfPTable table = CreatePDFUtil.setTable(tableVoObj);
		String currentStamp = DateAndStampUtil.getCurrentStamp();
		//标题，主题，关键字,作者，作者，文件名称
		String fileName = currentStamp+"_"+currentEmpNo;
		String param = tableName+"###系统#系统#"+fileName;
		CreatePDFUtil.createDocument(table,param);
		
		Map<String,String> rMap = new HashMap<String,String>();
		rMap.put("ipAddress", IP_ADDRESS);
		rMap.put("credential_type", "storage");
		rMap.put("storageNo", fileName);
		rMap.put("title", tableName);
		return rMap;
		
	}

	@Override
	public Map<String, Boolean> checkEmpAndBranch(HttpServletRequest request) {
		Map<String, Boolean> rMap = new HashMap<String, Boolean>();
		String empNo = request.getParameter("empNo");
		String branchNo = request.getParameter("branchNo");
		Integer userId = userMapper.queryUserIdByBranchAndEmp(empNo,branchNo);
		if(userId!=null && userId!=0){
			rMap.put("checkResult", true);
		}else{
			rMap.put("checkResult", false);
		}
		return rMap;
	}

	@Override
	public Map<String, Object> getRequestAndReturnInfo(HttpServletRequest request) {
		String branchNo = request.getParameter("branchNoByRequestReg");
		String branchNo2 = request.getParameter("branchNameByRequestReg");
		if(!"".equals(branchNo2)&&branchNo2!=null){
			branchNo = branchNo2;
		}else{
			if(branchNo!=null && "10000000".equals(branchNo)){
				branchNo = "";
			}
		}
		String storageDateFrom = request.getParameter("storageDateFromByRequestReg");
		String userNoToQuery = request.getParameter("empNoByRequestReg");
		String cardPName = request.getParameter("cardPNameByRequestReg");
		String requestOrReturn = request.getParameter("requestOrReturnByRequestReg");
		if(!"".equals(storageDateFrom)&&storageDateFrom!=null){
			storageDateFrom = storageDateFrom.replace("-", "");
		}
		String storageDateTo = request.getParameter("storageDateToByRequestReg");
		
		logger.debug("storageDateFrom==>"+storageDateFrom);
		logger.debug("storageDateTo==>"+storageDateTo);
		logger.debug("branchNo==>"+branchNo);
		logger.debug("userNoToQuery==>"+userNoToQuery);
		logger.debug("cardPName==>"+cardPName);
		logger.debug("requestOrReturn==>"+requestOrReturn);
		
		List<RequestAndReturnRegInfoByEmpVo> requestInfoList = new ArrayList<RequestAndReturnRegInfoByEmpVo>();
		requestInfoList = srm.queryRequestAndReturnOFEmpReg(branchNo,storageDateFrom,storageDateTo,userNoToQuery,cardPName,requestOrReturn);
		
		
		Map<String,Object> map = new HashMap<String,Object>();

		map.put("requestInfoList", requestInfoList);

		return map;
	}
}
